bindRolePermsLogic.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. newSet := make(map[int64]bool, len(permIds))
  66. for _, id := range permIds {
  67. newSet[id] = true
  68. }
  69. // 审计 M-R10-2:把 existing 读 + diff + delete/insert 整段收敛进事务,并以 LockByIdTx
  70. // 锁住 sys_role 行。两个并发的"完全覆盖 bind" 会在 role 行级别被串行化,"A 完成 → B 基于
  71. // A 的最终态重新覆盖"成为唯一可能的交错,彻底消除"A/B diff 各自的 toRemove/toAdd 在时间
  72. // 线上交织、最终态是两者都不想要的第三态"这一 RMW 类 bug。
  73. diffCounts := struct {
  74. add int
  75. remove int
  76. }{}
  77. if err := l.svcCtx.SysRolePermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  78. if _, err := l.svcCtx.SysRoleModel.LockByIdTx(ctx, session, req.RoleId); err != nil {
  79. return err
  80. }
  81. existingPermIds, err := l.svcCtx.SysRolePermModel.FindPermIdsByRoleIdTx(ctx, session, req.RoleId)
  82. if err != nil {
  83. return err
  84. }
  85. existingSet := make(map[int64]bool, len(existingPermIds))
  86. for _, id := range existingPermIds {
  87. existingSet[id] = true
  88. }
  89. var toAdd []int64
  90. for _, id := range permIds {
  91. if !existingSet[id] {
  92. toAdd = append(toAdd, id)
  93. }
  94. }
  95. var toRemove []int64
  96. for _, id := range existingPermIds {
  97. if !newSet[id] {
  98. toRemove = append(toRemove, id)
  99. }
  100. }
  101. diffCounts.add, diffCounts.remove = len(toAdd), len(toRemove)
  102. if len(toAdd) == 0 && len(toRemove) == 0 {
  103. return nil
  104. }
  105. if err := l.svcCtx.SysRolePermModel.DeleteByRoleIdAndPermIdsTx(ctx, session, req.RoleId, toRemove); err != nil {
  106. return err
  107. }
  108. if len(toAdd) > 0 {
  109. now := time.Now().Unix()
  110. data := make([]*roleperm.SysRolePerm, 0, len(toAdd))
  111. for _, permId := range toAdd {
  112. data = append(data, &roleperm.SysRolePerm{
  113. RoleId: req.RoleId,
  114. PermId: permId,
  115. CreateTime: now,
  116. UpdateTime: now,
  117. })
  118. }
  119. return l.svcCtx.SysRolePermModel.BatchInsertWithTx(ctx, session, data)
  120. }
  121. return nil
  122. }); err != nil {
  123. return err
  124. }
  125. if diffCounts.add == 0 && diffCounts.remove == 0 {
  126. return nil
  127. }
  128. // 事务已提交成功,缓存清理属于尽力而为:FindUserIdsByRoleId 失败仅记录 Errorf,
  129. // 不映射为 500——否则客户端会把"数据已改但缓存未刷"的 degraded 成功状态误判为完全失败
  130. // 而发起重试,重试时 diff 出的 toAdd/toRemove 均为空将静默 200,业务语义反而更怪
  131. // (见审计 M-4)。旧权限缓存最多在 TTL (5 分钟) 后自然过期,不影响正确性。
  132. if affectedUserIds, err := l.svcCtx.SysUserRoleModel.FindUserIdsByRoleId(l.ctx, req.RoleId); err == nil {
  133. l.svcCtx.UserDetailsLoader.BatchDel(l.ctx, affectedUserIds, role.ProductCode)
  134. } else {
  135. logx.WithContext(l.ctx).Errorf("BindRolePerms roleId=%d 角色权限已更新但 FindUserIdsByRoleId 失败,用户权限缓存将等待 TTL 自然过期: %v", req.RoleId, err)
  136. }
  137. return nil
  138. }