bindRolePermsLogic.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. if err := authHelper.RequireProductAdmin(l.ctx); err != nil {
  27. return err
  28. }
  29. role, err := l.svcCtx.SysRoleModel.FindOne(l.ctx, req.RoleId)
  30. if err != nil {
  31. return response.ErrNotFound("角色不存在")
  32. }
  33. if err := l.svcCtx.SysRolePermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  34. if err := l.svcCtx.SysRolePermModel.DeleteByRoleIdTx(ctx, session, req.RoleId); err != nil {
  35. return err
  36. }
  37. if len(req.PermIds) == 0 {
  38. return nil
  39. }
  40. now := time.Now().Unix()
  41. data := make([]*roleperm.SysRolePerm, 0, len(req.PermIds))
  42. for _, permId := range req.PermIds {
  43. data = append(data, &roleperm.SysRolePerm{
  44. RoleId: req.RoleId,
  45. PermId: permId,
  46. CreateTime: now,
  47. UpdateTime: now,
  48. })
  49. }
  50. return l.svcCtx.SysRolePermModel.BatchInsertWithTx(ctx, session, data)
  51. }); err != nil {
  52. return err
  53. }
  54. affectedUserIds, _ := l.svcCtx.SysUserRoleModel.FindUserIdsByRoleId(l.ctx, req.RoleId)
  55. l.svcCtx.UserDetailsLoader.BatchDel(l.ctx, affectedUserIds, role.ProductCode)
  56. return nil
  57. }