setUserPermsLogic.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package user
  2. import (
  3. "context"
  4. "time"
  5. authHelper "perms-system-server/internal/logic/auth"
  6. "perms-system-server/internal/middleware"
  7. "perms-system-server/internal/model/userperm"
  8. "perms-system-server/internal/response"
  9. "perms-system-server/internal/svc"
  10. "perms-system-server/internal/types"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "github.com/zeromicro/go-zero/core/stores/sqlx"
  13. )
  14. type SetUserPermsLogic struct {
  15. logx.Logger
  16. ctx context.Context
  17. svcCtx *svc.ServiceContext
  18. }
  19. func NewSetUserPermsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetUserPermsLogic {
  20. return &SetUserPermsLogic{
  21. Logger: logx.WithContext(ctx),
  22. ctx: ctx,
  23. svcCtx: svcCtx,
  24. }
  25. }
  26. func (l *SetUserPermsLogic) SetUserPerms(req *types.SetPermsReq) error {
  27. if _, err := l.svcCtx.SysUserModel.FindOne(l.ctx, req.UserId); err != nil {
  28. return response.ErrNotFound("用户不存在")
  29. }
  30. productCode := middleware.GetProductCode(l.ctx)
  31. if err := authHelper.CheckManageAccess(l.ctx, l.svcCtx, req.UserId, productCode); err != nil {
  32. return err
  33. }
  34. if err := l.svcCtx.SysUserPermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
  35. if err := l.svcCtx.SysUserPermModel.DeleteByUserIdTx(ctx, session, req.UserId); err != nil {
  36. return err
  37. }
  38. if len(req.Perms) == 0 {
  39. return nil
  40. }
  41. now := time.Now().Unix()
  42. data := make([]*userperm.SysUserPerm, 0, len(req.Perms))
  43. for _, p := range req.Perms {
  44. data = append(data, &userperm.SysUserPerm{
  45. UserId: req.UserId,
  46. PermId: p.PermId,
  47. Effect: p.Effect,
  48. CreateTime: now,
  49. UpdateTime: now,
  50. })
  51. }
  52. return l.svcCtx.SysUserPermModel.BatchInsertWithTx(ctx, session, data)
  53. }); err != nil {
  54. return err
  55. }
  56. l.svcCtx.UserDetailsLoader.Del(l.ctx, req.UserId, productCode)
  57. return nil
  58. }