bindRolePermsLogic.go 5.1 KB

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