bindRolePermsLogic.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package role
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "perms-system-server/internal/consts"
  7. "perms-system-server/internal/loaders"
  8. authHelper "perms-system-server/internal/logic/auth"
  9. "perms-system-server/internal/model/roleperm"
  10. "perms-system-server/internal/response"
  11. "perms-system-server/internal/svc"
  12. "perms-system-server/internal/types"
  13. "github.com/zeromicro/go-zero/core/logx"
  14. "github.com/zeromicro/go-zero/core/stores/sqlx"
  15. )
  16. type BindRolePermsLogic struct {
  17. logx.Logger
  18. ctx context.Context
  19. svcCtx *svc.ServiceContext
  20. }
  21. func NewBindRolePermsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindRolePermsLogic {
  22. return &BindRolePermsLogic{
  23. Logger: logx.WithContext(ctx),
  24. ctx: ctx,
  25. svcCtx: svcCtx,
  26. }
  27. }
  28. // BindRolePerms 绑定角色权限。对指定角色做权限全量覆盖(diff 后批量新增/删除),变更后自动清理该角色下所有用户的权限缓存。
  29. func (l *BindRolePermsLogic) BindRolePerms(req *types.BindPermsReq) error {
  30. // 审计 L-R14-1:非超管看到"非本产品 roleId"必须伪装成 404,避免 404 vs 403 文案
  31. // 差异泄漏跨产品 roleId 存在性。
  32. role, err := authHelper.ResolveOwnRoleOr404(l.ctx, l.svcCtx, req.RoleId)
  33. if err != nil {
  34. return err
  35. }
  36. if err := authHelper.RequireProductAdminFor(l.ctx, role.ProductCode); err != nil {
  37. return err
  38. }
  39. permIds := req.PermIds
  40. if len(permIds) > 0 {
  41. seen := make(map[int64]bool, len(permIds))
  42. uniqueIds := make([]int64, 0, len(permIds))
  43. for _, id := range permIds {
  44. if !seen[id] {
  45. seen[id] = true
  46. uniqueIds = append(uniqueIds, id)
  47. }
  48. }
  49. permIds = uniqueIds
  50. }
  51. if len(permIds) > 0 {
  52. perms, err := l.svcCtx.SysPermModel.FindByIds(l.ctx, permIds)
  53. if err != nil {
  54. return err
  55. }
  56. if len(perms) != len(permIds) {
  57. return response.ErrBadRequest("包含无效的权限ID")
  58. }
  59. for _, p := range perms {
  60. if p.ProductCode != role.ProductCode {
  61. return response.ErrBadRequest("不能绑定其他产品的权限")
  62. }
  63. if p.Status != consts.StatusEnabled {
  64. return response.ErrBadRequest(fmt.Sprintf("权限 %s 已被禁用,无法绑定", p.Code))
  65. }
  66. }
  67. }
  68. newSet := make(map[int64]bool, len(permIds))
  69. for _, id := range permIds {
  70. newSet[id] = true
  71. }
  72. // 审计 M-R10-2:把 existing 读 + diff + delete/insert 整段收敛进事务,并以 LockByIdTx
  73. // 锁住 sys_role 行。两个并发的"完全覆盖 bind" 会在 role 行级别被串行化,"A 完成 → B 基于
  74. // A 的最终态重新覆盖"成为唯一可能的交错,彻底消除"A/B diff 各自的 toRemove/toAdd 在时间
  75. // 线上交织、最终态是两者都不想要的第三态"这一 RMW 类 bug。
  76. diffCounts := struct {
  77. add int
  78. remove int
  79. }{}
  80. if err := l.svcCtx.SysRolePermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  81. if _, err := l.svcCtx.SysRoleModel.LockByIdTx(ctx, session, req.RoleId); err != nil {
  82. return err
  83. }
  84. existingPermIds, err := l.svcCtx.SysRolePermModel.FindPermIdsByRoleIdTx(ctx, session, req.RoleId)
  85. if err != nil {
  86. return err
  87. }
  88. existingSet := make(map[int64]bool, len(existingPermIds))
  89. for _, id := range existingPermIds {
  90. existingSet[id] = true
  91. }
  92. var toAdd []int64
  93. for _, id := range permIds {
  94. if !existingSet[id] {
  95. toAdd = append(toAdd, id)
  96. }
  97. }
  98. var toRemove []int64
  99. for _, id := range existingPermIds {
  100. if !newSet[id] {
  101. toRemove = append(toRemove, id)
  102. }
  103. }
  104. diffCounts.add, diffCounts.remove = len(toAdd), len(toRemove)
  105. if len(toAdd) == 0 && len(toRemove) == 0 {
  106. return nil
  107. }
  108. if err := l.svcCtx.SysRolePermModel.DeleteByRoleIdAndPermIdsTx(ctx, session, req.RoleId, toRemove); err != nil {
  109. return err
  110. }
  111. if len(toAdd) > 0 {
  112. now := time.Now().Unix()
  113. data := make([]*roleperm.SysRolePerm, 0, len(toAdd))
  114. for _, permId := range toAdd {
  115. data = append(data, &roleperm.SysRolePerm{
  116. RoleId: req.RoleId,
  117. PermId: permId,
  118. CreateTime: now,
  119. UpdateTime: now,
  120. })
  121. }
  122. return l.svcCtx.SysRolePermModel.BatchInsertWithTx(ctx, session, data)
  123. }
  124. return nil
  125. }); err != nil {
  126. return err
  127. }
  128. if diffCounts.add == 0 && diffCounts.remove == 0 {
  129. return nil
  130. }
  131. // 事务已提交成功,缓存清理属于尽力而为:FindUserIdsByRoleId 失败仅记录 Errorf,
  132. // 不映射为 500——否则客户端会把"数据已改但缓存未刷"的 degraded 成功状态误判为完全失败
  133. // 而发起重试,重试时 diff 出的 toAdd/toRemove 均为空将静默 200,业务语义反而更怪
  134. // (见审计 M-4)。旧权限缓存最多在 TTL (5 分钟) 后自然过期,不影响正确性。
  135. if affectedUserIds, err := l.svcCtx.SysUserRoleModel.FindUserIdsByRoleId(l.ctx, req.RoleId); err == nil {
  136. // 审计 L-R13-5 方案 A:角色权限集变更会让所有持有者的 loadPerms 输出改写;
  137. // BatchDel 的批量 Redis RTT 特别容易被请求 ctx 取消打断,这里 detach 出来。
  138. cleanCtx, cancel := loaders.DetachCacheCleanCtx(l.ctx)
  139. defer cancel()
  140. l.svcCtx.UserDetailsLoader.BatchDel(cleanCtx, affectedUserIds, role.ProductCode)
  141. } else {
  142. logx.WithContext(l.ctx).Errorf("BindRolePerms roleId=%d 角色权限已更新但 FindUserIdsByRoleId 失败,用户权限缓存将等待 TTL 自然过期: %v", req.RoleId, err)
  143. }
  144. return nil
  145. }