createUserLogic.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package user
  2. import (
  3. "context"
  4. "strings"
  5. "time"
  6. "perms-system-server/internal/consts"
  7. authHelper "perms-system-server/internal/logic/auth"
  8. "perms-system-server/internal/middleware"
  9. userModel "perms-system-server/internal/model/user"
  10. "perms-system-server/internal/response"
  11. "perms-system-server/internal/svc"
  12. "perms-system-server/internal/types"
  13. "perms-system-server/internal/util"
  14. "github.com/zeromicro/go-zero/core/logx"
  15. "golang.org/x/crypto/bcrypt"
  16. )
  17. type CreateUserLogic struct {
  18. logx.Logger
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. }
  22. func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
  23. return &CreateUserLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx,
  27. }
  28. }
  29. func (l *CreateUserLogic) CreateUser(req *types.CreateUserReq) (resp *types.IdResp, err error) {
  30. productCode := middleware.GetProductCode(l.ctx)
  31. if err := authHelper.RequireProductAdminFor(l.ctx, productCode); err != nil {
  32. return nil, err
  33. }
  34. if len(req.Password) < 6 {
  35. return nil, response.ErrBadRequest("密码长度不能少于6个字符")
  36. }
  37. if len(req.Password) > 72 {
  38. return nil, response.ErrBadRequest("密码长度不能超过72个字符")
  39. }
  40. if req.Email != "" && !util.IsValidEmail(req.Email) {
  41. return nil, response.ErrBadRequest("邮箱格式不正确")
  42. }
  43. if req.Phone != "" && !util.IsValidPhone(req.Phone) {
  44. return nil, response.ErrBadRequest("手机号格式不正确")
  45. }
  46. hashedPwd, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
  47. if err != nil {
  48. return nil, err
  49. }
  50. now := time.Now().Unix()
  51. result, err := l.svcCtx.SysUserModel.Insert(l.ctx, &userModel.SysUser{
  52. Username: req.Username,
  53. Password: string(hashedPwd),
  54. Nickname: req.Nickname,
  55. Email: req.Email,
  56. Phone: req.Phone,
  57. Remark: req.Remark,
  58. DeptId: req.DeptId,
  59. IsSuperAdmin: consts.IsSuperAdminNo,
  60. MustChangePassword: consts.MustChangePasswordNo,
  61. Status: consts.StatusEnabled,
  62. CreateTime: now,
  63. UpdateTime: now,
  64. })
  65. if err != nil {
  66. if strings.Contains(err.Error(), "1062") || strings.Contains(err.Error(), "Duplicate entry") {
  67. return nil, response.ErrConflict("用户名已存在")
  68. }
  69. return nil, err
  70. }
  71. id, _ := result.LastInsertId()
  72. return &types.IdResp{Id: id}, nil
  73. }