sys_role.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package service
  2. import (
  3. "errors"
  4. "github.com/go-admin-team/go-admin-core/sdk/config"
  5. "gorm.io/gorm/clause"
  6. "github.com/casbin/casbin/v2"
  7. "github.com/go-admin-team/go-admin-core/sdk/service"
  8. "gorm.io/gorm"
  9. "go-admin/app/admin/models"
  10. "go-admin/app/admin/service/dto"
  11. cDto "go-admin/common/dto"
  12. )
  13. type SysRole struct {
  14. service.Service
  15. }
  16. // GetPage 获取SysRole列表
  17. func (e *SysRole) GetPage(c *dto.SysRoleGetPageReq, list *[]models.SysRole, count *int64) error {
  18. var err error
  19. var data models.SysRole
  20. err = e.Orm.Model(&data).Preload("SysMenu").
  21. Scopes(
  22. cDto.MakeCondition(c.GetNeedSearch()),
  23. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  24. ).
  25. Find(list).Limit(-1).Offset(-1).
  26. Count(count).Error
  27. if err != nil {
  28. e.Log.Errorf("db error:%s", err)
  29. return err
  30. }
  31. return nil
  32. }
  33. // Get 获取SysRole对象
  34. func (e *SysRole) Get(d *dto.SysRoleGetReq, model *models.SysRole) error {
  35. var err error
  36. db := e.Orm.First(model, d.GetId())
  37. err = db.Error
  38. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  39. err = errors.New("查看对象不存在或无权查看")
  40. e.Log.Errorf("db error:%s", err)
  41. return err
  42. }
  43. if err != nil {
  44. e.Log.Errorf("db error:%s", err)
  45. return err
  46. }
  47. model.MenuIds, err = e.GetRoleMenuId(model.RoleId)
  48. if err != nil {
  49. e.Log.Errorf("get menuIds error, %s", err.Error())
  50. return err
  51. }
  52. return nil
  53. }
  54. // Insert 创建SysRole对象
  55. func (e *SysRole) Insert(c *dto.SysRoleInsertReq, cb *casbin.SyncedEnforcer) error {
  56. var err error
  57. var data models.SysRole
  58. var dataMenu []models.SysMenu
  59. err = e.Orm.Preload("SysApi").Where("menu_id in ?", c.MenuIds).Find(&dataMenu).Error
  60. if err != nil {
  61. e.Log.Errorf("db error:%s", err)
  62. return err
  63. }
  64. c.SysMenu = dataMenu
  65. c.Generate(&data)
  66. tx := e.Orm
  67. if config.DatabaseConfig.Driver != "sqlite3" {
  68. tx := e.Orm.Begin()
  69. defer func() {
  70. if err != nil {
  71. tx.Rollback()
  72. } else {
  73. tx.Commit()
  74. }
  75. }()
  76. }
  77. var count int64
  78. err = tx.Model(&data).Where("role_key = ?", c.RoleKey).Count(&count).Error
  79. if err != nil {
  80. e.Log.Errorf("db error:%s", err)
  81. return err
  82. }
  83. if count > 0 {
  84. err = errors.New("roleKey已存在,需更换在提交!")
  85. e.Log.Errorf("db error:%s", err)
  86. return err
  87. }
  88. err = tx.Create(&data).Error
  89. if err != nil {
  90. e.Log.Errorf("db error:%s", err)
  91. return err
  92. }
  93. mp := make(map[string]interface{}, 0)
  94. polices := make([][]string, 0)
  95. for _, menu := range dataMenu {
  96. for _, api := range menu.SysApi {
  97. if mp[data.RoleKey+"-"+api.Path+"-"+api.Action] != "" {
  98. mp[data.RoleKey+"-"+api.Path+"-"+api.Action] = ""
  99. polices = append(polices, []string{data.RoleKey, api.Path, api.Action})
  100. }
  101. }
  102. }
  103. if len(polices) <= 0 {
  104. return nil
  105. }
  106. _, err = cb.AddNamedPolicies("p", polices)
  107. if err != nil {
  108. return err
  109. }
  110. return nil
  111. }
  112. // Update 修改SysRole对象
  113. func (e *SysRole) Update(c *dto.SysRoleUpdateReq, cb *casbin.SyncedEnforcer) error {
  114. var err error
  115. tx := e.Orm
  116. if config.DatabaseConfig.Driver != "sqlite3" {
  117. tx := e.Orm.Begin()
  118. defer func() {
  119. if err != nil {
  120. tx.Rollback()
  121. } else {
  122. tx.Commit()
  123. }
  124. }()
  125. }
  126. var model = models.SysRole{}
  127. var mlist = make([]models.SysMenu, 0)
  128. tx.Preload("SysMenu").First(&model, c.GetId())
  129. tx.Preload("SysApi").Where("menu_id in ?", c.MenuIds).Find(&mlist)
  130. err = tx.Model(&model).Association("SysMenu").Delete(model.SysMenu)
  131. if err != nil {
  132. e.Log.Errorf("delete policy error:%s", err)
  133. return err
  134. }
  135. c.Generate(&model)
  136. model.SysMenu = &mlist
  137. db := tx.Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
  138. if err = db.Error; err != nil {
  139. e.Log.Errorf("db error:%s", err)
  140. return err
  141. }
  142. if db.RowsAffected == 0 {
  143. return errors.New("无权更新该数据")
  144. }
  145. _, err = cb.RemoveFilteredPolicy(0, model.RoleKey)
  146. if err != nil {
  147. e.Log.Errorf("delete policy error:%s", err)
  148. return err
  149. }
  150. mp := make(map[string]interface{}, 0)
  151. polices := make([][]string, 0)
  152. for _, menu := range mlist {
  153. for _, api := range menu.SysApi {
  154. if mp[model.RoleKey+"-"+api.Path+"-"+api.Action] != "" {
  155. mp[model.RoleKey+"-"+api.Path+"-"+api.Action] = ""
  156. //_, err = cb.AddNamedPolicy("p", model.RoleKey, api.Path, api.Action)
  157. polices = append(polices, []string{model.RoleKey, api.Path, api.Action})
  158. }
  159. }
  160. }
  161. if len(polices) <= 0 {
  162. return nil
  163. }
  164. _, err = cb.AddNamedPolicies("p", polices)
  165. if err != nil {
  166. return err
  167. }
  168. return nil
  169. }
  170. // Remove 删除SysRole
  171. func (e *SysRole) Remove(c *dto.SysRoleDeleteReq, cb *casbin.SyncedEnforcer) error {
  172. var err error
  173. tx := e.Orm
  174. if config.DatabaseConfig.Driver != "sqlite3" {
  175. tx := e.Orm.Begin()
  176. defer func() {
  177. if err != nil {
  178. tx.Rollback()
  179. } else {
  180. tx.Commit()
  181. }
  182. }()
  183. }
  184. var model = models.SysRole{}
  185. tx.Preload("SysMenu").Preload("SysDept").First(&model, c.GetId())
  186. db := tx.Select(clause.Associations).Delete(&model)
  187. if err = db.Error; err != nil {
  188. e.Log.Errorf("db error:%s", err)
  189. return err
  190. }
  191. if db.RowsAffected == 0 {
  192. return errors.New("无权更新该数据")
  193. }
  194. _, _ = cb.RemoveFilteredPolicy(0, model.RoleKey)
  195. return nil
  196. }
  197. // GetRoleMenuId 获取角色对应的菜单ids
  198. func (e *SysRole) GetRoleMenuId(roleId int) ([]int, error) {
  199. menuIds := make([]int, 0)
  200. model := models.SysRole{}
  201. model.RoleId = roleId
  202. if err := e.Orm.Model(&model).Preload("SysMenu").First(&model).Error; err != nil {
  203. return nil, err
  204. }
  205. l := *model.SysMenu
  206. for i := 0; i < len(l); i++ {
  207. menuIds = append(menuIds, l[i].MenuId)
  208. }
  209. return menuIds, nil
  210. }
  211. func (e *SysRole) UpdateDataScope(c *dto.RoleDataScopeReq) *SysRole {
  212. var err error
  213. tx := e.Orm
  214. if config.DatabaseConfig.Driver != "sqlite3" {
  215. tx := e.Orm.Begin()
  216. defer func() {
  217. if err != nil {
  218. tx.Rollback()
  219. } else {
  220. tx.Commit()
  221. }
  222. }()
  223. }
  224. var dlist = make([]models.SysDept, 0)
  225. var model = models.SysRole{}
  226. tx.Preload("SysDept").First(&model, c.RoleId)
  227. tx.Where("dept_id in ?", c.DeptIds).Find(&dlist)
  228. err = tx.Model(&model).Association("SysDept").Delete(model.SysDept)
  229. if err != nil {
  230. e.Log.Errorf("delete SysDept error:%s", err)
  231. _ = e.AddError(err)
  232. return e
  233. }
  234. c.Generate(&model)
  235. model.SysDept = dlist
  236. db := tx.Model(&model).Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
  237. if err = db.Error; err != nil {
  238. e.Log.Errorf("db error:%s", err)
  239. _ = e.AddError(err)
  240. return e
  241. }
  242. if db.RowsAffected == 0 {
  243. _ = e.AddError(errors.New("无权更新该数据"))
  244. return e
  245. }
  246. return e
  247. }
  248. // UpdateStatus 修改SysRole对象status
  249. func (e *SysRole) UpdateStatus(c *dto.UpdateStatusReq) error {
  250. var err error
  251. tx := e.Orm
  252. if config.DatabaseConfig.Driver != "sqlite3" {
  253. tx := e.Orm.Begin()
  254. defer func() {
  255. if err != nil {
  256. tx.Rollback()
  257. } else {
  258. tx.Commit()
  259. }
  260. }()
  261. }
  262. var model = models.SysRole{}
  263. tx.First(&model, c.GetId())
  264. c.Generate(&model)
  265. db := tx.Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
  266. if err = db.Error; err != nil {
  267. e.Log.Errorf("db error:%s", err)
  268. return err
  269. }
  270. if db.RowsAffected == 0 {
  271. return errors.New("无权更新该数据")
  272. }
  273. return nil
  274. }
  275. // GetWithName 获取SysRole对象
  276. func (e *SysRole) GetWithName(d *dto.SysRoleByName, model *models.SysRole) *SysRole {
  277. var err error
  278. db := e.Orm.Where("role_name = ?", d.RoleName).First(model)
  279. err = db.Error
  280. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  281. err = errors.New("查看对象不存在或无权查看")
  282. e.Log.Errorf("db error:%s", err)
  283. _ = e.AddError(err)
  284. return e
  285. }
  286. if err != nil {
  287. e.Log.Errorf("db error:%s", err)
  288. _ = e.AddError(err)
  289. return e
  290. }
  291. model.MenuIds, err = e.GetRoleMenuId(model.RoleId)
  292. if err != nil {
  293. e.Log.Errorf("get menuIds error, %s", err.Error())
  294. _ = e.AddError(err)
  295. return e
  296. }
  297. return e
  298. }
  299. // GetById 获取SysRole对象
  300. func (e *SysRole) GetById(roleId int) ([]string, error) {
  301. permissions := make([]string, 0)
  302. model := models.SysRole{}
  303. model.RoleId = roleId
  304. if err := e.Orm.Model(&model).Preload("SysMenu").First(&model).Error; err != nil {
  305. return nil, err
  306. }
  307. l := *model.SysMenu
  308. for i := 0; i < len(l); i++ {
  309. permissions = append(permissions, l[i].Permission)
  310. }
  311. return permissions, nil
  312. }