bindRolePermsLogic.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package role
  2. import (
  3. "context"
  4. "time"
  5. authHelper "perms-system-server/internal/logic/auth"
  6. "perms-system-server/internal/model/roleperm"
  7. "perms-system-server/internal/response"
  8. "perms-system-server/internal/svc"
  9. "perms-system-server/internal/types"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "github.com/zeromicro/go-zero/core/stores/sqlx"
  12. )
  13. type BindRolePermsLogic struct {
  14. logx.Logger
  15. ctx context.Context
  16. svcCtx *svc.ServiceContext
  17. }
  18. func NewBindRolePermsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindRolePermsLogic {
  19. return &BindRolePermsLogic{
  20. Logger: logx.WithContext(ctx),
  21. ctx: ctx,
  22. svcCtx: svcCtx,
  23. }
  24. }
  25. func (l *BindRolePermsLogic) BindRolePerms(req *types.BindPermsReq) error {
  26. role, err := l.svcCtx.SysRoleModel.FindOne(l.ctx, req.RoleId)
  27. if err != nil {
  28. return response.ErrNotFound("角色不存在")
  29. }
  30. if err := authHelper.RequireProductAdminFor(l.ctx, role.ProductCode); err != nil {
  31. return err
  32. }
  33. if len(req.PermIds) > 0 {
  34. perms, err := l.svcCtx.SysPermModel.FindByIds(l.ctx, req.PermIds)
  35. if err != nil {
  36. return err
  37. }
  38. if len(perms) != len(req.PermIds) {
  39. return response.ErrBadRequest("包含无效的权限ID")
  40. }
  41. for _, p := range perms {
  42. if p.ProductCode != role.ProductCode {
  43. return response.ErrBadRequest("不能绑定其他产品的权限")
  44. }
  45. }
  46. }
  47. if err := l.svcCtx.SysRolePermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  48. if err := l.svcCtx.SysRolePermModel.DeleteByRoleIdTx(ctx, session, req.RoleId); err != nil {
  49. return err
  50. }
  51. if len(req.PermIds) == 0 {
  52. return nil
  53. }
  54. now := time.Now().Unix()
  55. data := make([]*roleperm.SysRolePerm, 0, len(req.PermIds))
  56. for _, permId := range req.PermIds {
  57. data = append(data, &roleperm.SysRolePerm{
  58. RoleId: req.RoleId,
  59. PermId: permId,
  60. CreateTime: now,
  61. UpdateTime: now,
  62. })
  63. }
  64. return l.svcCtx.SysRolePermModel.BatchInsertWithTx(ctx, session, data)
  65. }); err != nil {
  66. return err
  67. }
  68. affectedUserIds, _ := l.svcCtx.SysUserRoleModel.FindUserIdsByRoleId(l.ctx, req.RoleId)
  69. l.svcCtx.UserDetailsLoader.BatchDel(l.ctx, affectedUserIds, role.ProductCode)
  70. return nil
  71. }