bindRolePermsLogic.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package role
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "perms-system-server/internal/consts"
  7. authHelper "perms-system-server/internal/logic/auth"
  8. "perms-system-server/internal/model/roleperm"
  9. "perms-system-server/internal/response"
  10. "perms-system-server/internal/svc"
  11. "perms-system-server/internal/types"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. "github.com/zeromicro/go-zero/core/stores/sqlx"
  14. )
  15. type BindRolePermsLogic struct {
  16. logx.Logger
  17. ctx context.Context
  18. svcCtx *svc.ServiceContext
  19. }
  20. func NewBindRolePermsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindRolePermsLogic {
  21. return &BindRolePermsLogic{
  22. Logger: logx.WithContext(ctx),
  23. ctx: ctx,
  24. svcCtx: svcCtx,
  25. }
  26. }
  27. // BindRolePerms 绑定角色权限。对指定角色做权限全量覆盖(diff 后批量新增/删除),变更后自动清理该角色下所有用户的权限缓存。
  28. func (l *BindRolePermsLogic) BindRolePerms(req *types.BindPermsReq) error {
  29. role, err := l.svcCtx.SysRoleModel.FindOne(l.ctx, req.RoleId)
  30. if err != nil {
  31. return response.ErrNotFound("角色不存在")
  32. }
  33. if err := authHelper.RequireProductAdminFor(l.ctx, role.ProductCode); err != nil {
  34. return err
  35. }
  36. permIds := req.PermIds
  37. if len(permIds) > 0 {
  38. seen := make(map[int64]bool, len(permIds))
  39. uniqueIds := make([]int64, 0, len(permIds))
  40. for _, id := range permIds {
  41. if !seen[id] {
  42. seen[id] = true
  43. uniqueIds = append(uniqueIds, id)
  44. }
  45. }
  46. permIds = uniqueIds
  47. }
  48. if len(permIds) > 0 {
  49. perms, err := l.svcCtx.SysPermModel.FindByIds(l.ctx, permIds)
  50. if err != nil {
  51. return err
  52. }
  53. if len(perms) != len(permIds) {
  54. return response.ErrBadRequest("包含无效的权限ID")
  55. }
  56. for _, p := range perms {
  57. if p.ProductCode != role.ProductCode {
  58. return response.ErrBadRequest("不能绑定其他产品的权限")
  59. }
  60. if p.Status != consts.StatusEnabled {
  61. return response.ErrBadRequest(fmt.Sprintf("权限 %s 已被禁用,无法绑定", p.Code))
  62. }
  63. }
  64. }
  65. existingPermIds, err := l.svcCtx.SysRolePermModel.FindPermIdsByRoleId(l.ctx, req.RoleId)
  66. if err != nil {
  67. return err
  68. }
  69. existingSet := make(map[int64]bool, len(existingPermIds))
  70. for _, id := range existingPermIds {
  71. existingSet[id] = true
  72. }
  73. newSet := make(map[int64]bool, len(permIds))
  74. for _, id := range permIds {
  75. newSet[id] = true
  76. }
  77. var toAdd []int64
  78. for _, id := range permIds {
  79. if !existingSet[id] {
  80. toAdd = append(toAdd, id)
  81. }
  82. }
  83. var toRemove []int64
  84. for _, id := range existingPermIds {
  85. if !newSet[id] {
  86. toRemove = append(toRemove, id)
  87. }
  88. }
  89. if len(toAdd) == 0 && len(toRemove) == 0 {
  90. return nil
  91. }
  92. if err := l.svcCtx.SysRolePermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  93. if err := l.svcCtx.SysRolePermModel.DeleteByRoleIdAndPermIdsTx(ctx, session, req.RoleId, toRemove); err != nil {
  94. return err
  95. }
  96. if len(toAdd) > 0 {
  97. now := time.Now().Unix()
  98. data := make([]*roleperm.SysRolePerm, 0, len(toAdd))
  99. for _, permId := range toAdd {
  100. data = append(data, &roleperm.SysRolePerm{
  101. RoleId: req.RoleId,
  102. PermId: permId,
  103. CreateTime: now,
  104. UpdateTime: now,
  105. })
  106. }
  107. return l.svcCtx.SysRolePermModel.BatchInsertWithTx(ctx, session, data)
  108. }
  109. return nil
  110. }); err != nil {
  111. return err
  112. }
  113. // 事务已提交成功,缓存清理属于尽力而为:FindUserIdsByRoleId 失败仅记录 Errorf,
  114. // 不映射为 500——否则客户端会把"数据已改但缓存未刷"的 degraded 成功状态误判为完全失败
  115. // 而发起重试,重试时 diff 出的 toAdd/toRemove 均为空将静默 200,业务语义反而更怪
  116. // (见审计 M-4)。旧权限缓存最多在 TTL (5 分钟) 后自然过期,不影响正确性。
  117. if affectedUserIds, err := l.svcCtx.SysUserRoleModel.FindUserIdsByRoleId(l.ctx, req.RoleId); err == nil {
  118. l.svcCtx.UserDetailsLoader.BatchDel(l.ctx, affectedUserIds, role.ProductCode)
  119. } else {
  120. logx.WithContext(l.ctx).Errorf("BindRolePerms roleId=%d 角色权限已更新但 FindUserIdsByRoleId 失败,用户权限缓存将等待 TTL 自然过期: %v", req.RoleId, err)
  121. }
  122. return nil
  123. }