createUserLogic.go 2.4 KB

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