sys_role.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package service
  2. import (
  3. "cold-delivery/common/actions"
  4. cDto "cold-delivery/common/dto"
  5. "cold-delivery/common/global"
  6. "errors"
  7. "fmt"
  8. "github.com/casbin/casbin/v2"
  9. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  10. "gogs.baozhida.cn/zoie/OAuth-core/pkg/utils"
  11. "gogs.baozhida.cn/zoie/OAuth-core/service"
  12. "strings"
  13. "cold-delivery/app/admin/model"
  14. "cold-delivery/app/admin/service/dto"
  15. "gorm.io/gorm"
  16. )
  17. type SysRole struct {
  18. service.Service
  19. }
  20. // GetPage 获取SysRole列表
  21. func (e *SysRole) GetPage(c *dto.SysRoleGetPageReq, list *[]model.SysRole, count *int64, p *actions.DataPermission) error {
  22. var err error
  23. var data model.SysRole
  24. err = e.Orm.Model(&data).
  25. Scopes(
  26. cDto.MakeCondition(c.GetNeedSearch()),
  27. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  28. actions.Permission(data.TableName(), p),
  29. ).
  30. Find(list).Limit(-1).Offset(-1).
  31. Count(count).Error
  32. if err != nil {
  33. e.Log.Errorf("db error: %s", err)
  34. return global.GetFailedErr
  35. }
  36. return nil
  37. }
  38. // Get 获取SysRole对象
  39. func (e *SysRole) Get(d *dto.SysRoleGetReq, roleModel *model.SysRole, p *actions.DataPermission) error {
  40. err := e.Orm.
  41. Scopes(actions.Permission(roleModel.TableName(), p)).
  42. First(roleModel, d.GetId()).Error
  43. if err != nil {
  44. e.Log.Errorf("db error: %s", err)
  45. if errors.Is(err, gorm.ErrRecordNotFound) {
  46. return global.GetNotFoundOrNoPermissionErr
  47. }
  48. return global.GetFailedErr
  49. }
  50. roleModel.MenuIds, err = e.GetRoleMenuId(roleModel.Id)
  51. if err != nil {
  52. e.Log.Errorf("get menuIds error, %s", err)
  53. return global.GetFailedErr
  54. }
  55. return nil
  56. }
  57. // Insert 创建SysRole对象
  58. func (e *SysRole) Insert(c *dto.SysRoleInsertReq) error {
  59. var err error
  60. var data model.SysRole
  61. tx := e.Orm.Begin()
  62. defer func() {
  63. if err != nil {
  64. tx.Rollback()
  65. } else {
  66. tx.Commit()
  67. }
  68. }()
  69. var roleKey string
  70. for {
  71. var count int64
  72. roleKey = utils.GetRandString(8, "", 0)
  73. var i int64
  74. err = tx.Model(&data).Where("role_key = ?", roleKey).Count(&count).Error
  75. if err != nil {
  76. continue
  77. }
  78. if i == 0 {
  79. break
  80. }
  81. }
  82. // 添加角色
  83. c.Generate(&data)
  84. data.RoleKey = roleKey
  85. err = tx.Create(&data).Error
  86. if err != nil {
  87. e.Log.Errorf("db error: %s", err)
  88. return global.CreateFailedErr
  89. }
  90. c.Id = data.Id
  91. // 添加角色菜单关联
  92. var menuList []model.SysMenu
  93. err = e.Orm.Where("id in (?)", c.MenuIds).Find(&menuList).Error
  94. if err != nil {
  95. return global.GetFailedErr
  96. }
  97. if len(menuList) == 0 {
  98. return errors.New("菜单不存在!")
  99. }
  100. var roleMenuList []model.SysRoleMenu
  101. // 添加角色关联的菜单
  102. for _, v := range menuList {
  103. roleMenuObj := model.SysRoleMenu{
  104. RoleKey: data.RoleKey,
  105. MenuId: v.Id,
  106. }
  107. roleMenuObj.SetCreateBy(c.CreateBy)
  108. roleMenuList = append(roleMenuList, roleMenuObj)
  109. }
  110. err = tx.Save(&roleMenuList).Error
  111. if err != nil {
  112. e.Log.Errorf("save menuIds error, %s", err)
  113. return global.UpdateFailedErr
  114. }
  115. return nil
  116. }
  117. // Update 修改SysRole对象
  118. func (e *SysRole) Update(c *dto.SysRoleUpdateReq, p *actions.DataPermission) error {
  119. var err error
  120. tx := e.Orm.Begin()
  121. defer func() {
  122. if err != nil {
  123. tx.Rollback()
  124. } else {
  125. tx.Commit()
  126. }
  127. }()
  128. var roleModel = model.SysRole{}
  129. // 查询角色是否存在
  130. err = e.Orm.Scopes(actions.Permission(roleModel.TableName(), p)).
  131. First(&roleModel, c.GetId()).Error
  132. if err != nil {
  133. e.Log.Errorf("db error: %s", err)
  134. if errors.Is(err, gorm.ErrRecordNotFound) {
  135. return global.UpdateNotFoundOrNoPermissionErr
  136. }
  137. return global.UpdateFailedErr
  138. }
  139. c.Generate(&roleModel)
  140. err = tx.Save(&roleModel).Error
  141. if err != nil {
  142. if errors.Is(err, model.ErrForbidUpdateSysRole) {
  143. return err
  144. }
  145. e.Log.Errorf("db error: %s", err)
  146. return global.UpdateFailedErr
  147. }
  148. // 删除角色关联的菜单
  149. err = tx.Where("role_key = ?", roleModel.RoleKey).Delete(&model.SysRoleMenu{}).Error
  150. if err != nil {
  151. e.Log.Errorf("db error: %s", err)
  152. return global.UpdateFailedErr
  153. }
  154. var menuList []model.SysMenu
  155. err = e.Orm.Where("id in (?)", c.MenuIds).Find(&menuList).Error
  156. if err != nil {
  157. return global.GetFailedErr
  158. }
  159. if len(menuList) == 0 {
  160. return errors.New("菜单不存在!")
  161. }
  162. var roleMenuList []model.SysRoleMenu
  163. // 添加角色关联的菜单
  164. for _, v := range menuList {
  165. roleMenuObj := model.SysRoleMenu{
  166. RoleKey: roleModel.RoleKey,
  167. MenuId: v.Id,
  168. }
  169. roleMenuObj.SetCreateBy(c.UpdateBy)
  170. roleMenuList = append(roleMenuList, roleMenuObj)
  171. }
  172. err = tx.Save(&roleMenuList).Error
  173. if err != nil {
  174. e.Log.Errorf("save menuIds error, %s", err)
  175. return global.UpdateFailedErr
  176. }
  177. if err := model.DeleteRoleMenuCache(roleModel.RoleKey); err != nil {
  178. e.Log.Errorf("delete role menu cache error, %s", err)
  179. return global.UpdateFailedErr
  180. }
  181. model.DeleteRoleMenuCache(model.GetRoleMenuCacheKey(roleModel.RoleKey) + "-0")
  182. model.DeleteRoleMenuCache(model.GetRoleMenuCacheKey(roleModel.RoleKey) + "-1")
  183. //redisClient := storage.GetRedisClient()
  184. ////获取相似的 Key
  185. //keys, err := redisClient.Keys("/" + model.GetRoleMenuCacheKey(roleModel.RoleKey) + "*").Result()
  186. //if err != nil {
  187. // return global.UpdateFailedErr
  188. //}
  189. ////删除相似的 Key
  190. //if len(keys) > 0 {
  191. // _, err = redisClient.Del(keys...).Result()
  192. // if err != nil {
  193. // return global.UpdateFailedErr
  194. // }
  195. //}
  196. c.Id = roleModel.Id
  197. return nil
  198. }
  199. // Remove 删除SysRole
  200. func (e *SysRole) Remove(c *dto.SysRoleDeleteReq, p *actions.DataPermission, cb *casbin.SyncedEnforcer) error {
  201. var err error
  202. tx := e.Orm.Begin()
  203. defer func() {
  204. if err != nil {
  205. tx.Rollback()
  206. } else {
  207. tx.Commit()
  208. }
  209. }()
  210. var userList = make([]model.SysUser, 0)
  211. var roleModel model.SysRole
  212. err = e.Orm.Where("role_id = ?", c.Id).Find(&userList).Error
  213. if err != nil {
  214. e.Log.Errorf("db error: %s", err)
  215. return global.DeleteFailedErr
  216. }
  217. // 统计与用户关联的角色名
  218. if len(userList) > 0 {
  219. var roleNameStr string
  220. for i := 0; i < len(userList); i++ {
  221. roleNameStr += fmt.Sprintf(" %s,", userList[i].Username)
  222. }
  223. if !pkg.IsEmptyStr(roleNameStr) {
  224. // eg: role1,role2有用户关联,禁止删除!
  225. return errors.New(strings.TrimRight(roleNameStr, ",") + "有用户关联,禁止删除!")
  226. }
  227. }
  228. // 查询角色是否存在
  229. err = e.Orm.Scopes(actions.Permission(roleModel.TableName(), p)).
  230. First(&roleModel, c.GetId()).Error
  231. if err != nil {
  232. e.Log.Errorf("db error: %s", err)
  233. if errors.Is(err, gorm.ErrRecordNotFound) {
  234. return global.DeleteNotFoundOrNoPermissionErr
  235. }
  236. return global.DeleteFailedErr
  237. }
  238. db := tx.Delete(&roleModel)
  239. if err = db.Error; err != nil {
  240. if errors.Is(err, model.ErrForbidDeleteSysRole) {
  241. return err
  242. }
  243. e.Log.Errorf("db error: %s", err)
  244. return global.DeleteFailedErr
  245. }
  246. if db.RowsAffected == 0 {
  247. return global.DeleteNotFoundOrNoPermissionErr
  248. }
  249. // 删除之前的角色关联的菜单
  250. var roleMenu model.SysRoleMenu
  251. err = tx.Where("role_key = ?", roleModel.RoleKey).Delete(&roleMenu).Error
  252. if err != nil {
  253. return global.UpdateFailedErr
  254. }
  255. // 清除 sys_casbin_rule 权限表里 当前角色的所有记录
  256. _, _ = cb.RemoveFilteredPolicy(0, roleModel.RoleKey)
  257. return nil
  258. }
  259. // GetRoleMenuId 获取角色对应的菜单ids
  260. func (e *SysRole) GetRoleMenuId(roleId int) ([]int, error) {
  261. var err error
  262. var roleModel model.SysRole
  263. var menuIds []int
  264. err = e.Orm.Where("id = ?", roleId).First(&roleModel).Error
  265. if err != nil {
  266. return []int{}, global.GetFailedErr
  267. }
  268. err = e.Orm.Model(&model.SysRoleMenu{}).Select("menu_id").Where("role_key = ? ", roleModel.RoleKey).Scan(&menuIds).Error
  269. if err != nil {
  270. return []int{}, global.GetFailedErr
  271. }
  272. return menuIds, nil
  273. }
  274. // GetWithName 获取SysRole对象
  275. func (e *SysRole) GetWithName(d *dto.SysRoleByName, roleModel *model.SysRole) *SysRole {
  276. err := e.Orm.Where("name = ?", d.RoleName).First(roleModel).Error
  277. if err != nil {
  278. e.Log.Errorf("db error: %s", err)
  279. if errors.Is(err, gorm.ErrRecordNotFound) {
  280. err = global.GetNotFoundOrNoPermissionErr
  281. } else {
  282. err = global.GetFailedErr
  283. }
  284. _ = e.AddError(err)
  285. return e
  286. }
  287. //roleModel.MenuIds, err = e.GetRoleMenuId(roleModel.Id)
  288. if err != nil {
  289. e.Log.Errorf("get menuIds error, %s", err.Error())
  290. _ = e.AddError(global.GetFailedErr)
  291. return e
  292. }
  293. return e
  294. }
  295. // GetById 获取SysRole对象
  296. func (e *SysRole) GetById(roleId int) ([]string, error) {
  297. permissions := make([]string, 0)
  298. roleModel := model.SysRole{}
  299. roleModel.Id = roleId
  300. err := e.Orm.Model(&roleModel).First(&roleModel).Error
  301. if err != nil {
  302. e.Log.Errorf("db error: %s", err)
  303. if errors.Is(err, gorm.ErrRecordNotFound) {
  304. err = global.GetNotFoundOrNoPermissionErr
  305. } else {
  306. err = global.GetFailedErr
  307. }
  308. return nil, err
  309. }
  310. //l := *roleModel.SysMenu
  311. //for i := 0; i < len(l); i++ {
  312. // permissions = append(permissions, l[i].Title)
  313. //}
  314. return permissions, nil
  315. }
  316. // UpdateRoleMenu 修改角色绑定的菜单
  317. func (e *SysRole) UpdateRoleMenu(d *dto.SysRoleUpdateRoleMenuReq) error {
  318. var err error
  319. tx := e.Orm.Begin()
  320. defer func() {
  321. if err != nil {
  322. tx.Rollback()
  323. } else {
  324. tx.Commit()
  325. }
  326. }()
  327. var roleModel model.SysRole
  328. err = e.Orm.Where("id = ?", d.GetId()).First(&roleModel).Error
  329. if err != nil {
  330. return global.GetFailedErr
  331. }
  332. var menuList []model.SysMenu
  333. err = e.Orm.Where("id in (?)", d.MenuIds).Find(&menuList).Error
  334. if err != nil {
  335. return global.GetFailedErr
  336. }
  337. if len(menuList) == 0 {
  338. return errors.New("菜单不存在!")
  339. }
  340. // 删除之前的角色关联的菜单
  341. var roleMenu model.SysRoleMenu
  342. err = tx.Where("role_key = ?", roleModel.RoleKey).Delete(&roleMenu).Error
  343. if err != nil {
  344. return global.UpdateFailedErr
  345. }
  346. var roleMenuList []model.SysRoleMenu
  347. // 添加角色关联的菜单
  348. for _, v := range menuList {
  349. roleMenuObj := model.SysRoleMenu{
  350. RoleKey: roleModel.RoleKey,
  351. MenuId: v.Id,
  352. }
  353. roleMenuObj.SetCreateBy(d.CreateBy)
  354. roleMenuList = append(roleMenuList, roleMenuObj)
  355. }
  356. err = tx.Save(&roleMenuList).Error
  357. if err != nil {
  358. e.Log.Errorf("save menuIds error, %s", err)
  359. return global.UpdateFailedErr
  360. }
  361. return nil
  362. }