sys_role.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * @desc:角色处理
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu
  5. * @Date: 2022/3/9 10:31
  6. */
  7. package service
  8. import (
  9. "context"
  10. "fmt"
  11. "github.com/gogf/gf/v2/frame/g"
  12. "github.com/gogf/gf/v2/util/gconv"
  13. commonService "github.com/tiger1103/gfast/v3/internal/app/common/service"
  14. "github.com/tiger1103/gfast/v3/internal/app/system/consts"
  15. "github.com/tiger1103/gfast/v3/internal/app/system/model/entity"
  16. "github.com/tiger1103/gfast/v3/internal/app/system/service/internal/dao"
  17. "github.com/tiger1103/gfast/v3/library/liberr"
  18. )
  19. type IRole interface {
  20. GetRoleList(ctx context.Context) (list []*entity.SysRole, err error)
  21. }
  22. type roleImpl struct {
  23. }
  24. var role = roleImpl{}
  25. func Role() IRole {
  26. return IRole(&role)
  27. }
  28. // GetRoleList 获取角色列表
  29. func (s *roleImpl) GetRoleList(ctx context.Context) (list []*entity.SysRole, err error) {
  30. cache := commonService.Cache(ctx)
  31. //从缓存获取
  32. iList := cache.GetOrSetFuncLock(ctx, consts.CacheSysRole, s.getRoleListFromDb, 0, consts.CacheSysAuthTag)
  33. if iList != nil {
  34. err = gconv.Struct(iList, &list)
  35. }
  36. return
  37. }
  38. // 从数据库获取所有角色
  39. func (s *roleImpl) getRoleListFromDb(ctx context.Context) (value interface{}, err error) {
  40. err = g.Try(func() {
  41. var v []*entity.SysRole
  42. //从数据库获取
  43. err = dao.SysRole.Ctx(ctx).
  44. Order(dao.SysRole.Columns().ListOrder + " asc," + dao.SysRole.Columns().Id + " asc").
  45. Scan(&v)
  46. liberr.ErrIsNil(ctx, err, "获取角色数据失败")
  47. value = v
  48. })
  49. return
  50. }
  51. // AddRoleRule 添加角色权限
  52. func (s *roleImpl) AddRoleRule(ctx context.Context, iRule interface{}, roleId int64) (err error) {
  53. err = g.Try(func() {
  54. enforcer, e := commonService.CasbinEnforcer(ctx)
  55. liberr.ErrIsNil(ctx, e)
  56. rule := gconv.Strings(iRule)
  57. for _, v := range rule {
  58. _, err = enforcer.AddPolicy(fmt.Sprintf("%d", roleId), fmt.Sprintf("%s", v), "All")
  59. liberr.ErrIsNil(ctx, err)
  60. }
  61. })
  62. return
  63. }