| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package user
- import (
- "context"
- "strings"
- "time"
- "perms-system-server/internal/consts"
- authHelper "perms-system-server/internal/logic/auth"
- userModel "perms-system-server/internal/model/user"
- "perms-system-server/internal/response"
- "perms-system-server/internal/svc"
- "perms-system-server/internal/types"
- "perms-system-server/internal/util"
- "github.com/zeromicro/go-zero/core/logx"
- "golang.org/x/crypto/bcrypt"
- )
- type CreateUserLogic struct {
- logx.Logger
- ctx context.Context
- svcCtx *svc.ServiceContext
- }
- func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
- return &CreateUserLogic{
- Logger: logx.WithContext(ctx),
- ctx: ctx,
- svcCtx: svcCtx,
- }
- }
- func (l *CreateUserLogic) CreateUser(req *types.CreateUserReq) (resp *types.IdResp, err error) {
- if err := authHelper.RequireProductAdmin(l.ctx); err != nil {
- return nil, err
- }
- if len(req.Password) < 6 {
- return nil, response.ErrBadRequest("密码长度不能少于6个字符")
- }
- if len(req.Password) > 72 {
- return nil, response.ErrBadRequest("密码长度不能超过72个字符")
- }
- if req.Email != "" && !util.IsValidEmail(req.Email) {
- return nil, response.ErrBadRequest("邮箱格式不正确")
- }
- if req.Phone != "" && !util.IsValidPhone(req.Phone) {
- return nil, response.ErrBadRequest("手机号格式不正确")
- }
- _, findErr := l.svcCtx.SysUserModel.FindOneByUsername(l.ctx, req.Username)
- if findErr == nil {
- return nil, response.ErrConflict("用户名已存在")
- }
- hashedPwd, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
- if err != nil {
- return nil, err
- }
- now := time.Now().Unix()
- result, err := l.svcCtx.SysUserModel.Insert(l.ctx, &userModel.SysUser{
- Username: req.Username,
- Password: string(hashedPwd),
- Nickname: req.Nickname,
- Email: req.Email,
- Phone: req.Phone,
- Remark: req.Remark,
- DeptId: req.DeptId,
- IsSuperAdmin: consts.IsSuperAdminNo,
- MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled,
- CreateTime: now,
- UpdateTime: now,
- })
- if err != nil {
- if strings.Contains(err.Error(), "1062") || strings.Contains(err.Error(), "Duplicate entry") {
- return nil, response.ErrConflict("用户名已存在")
- }
- return nil, err
- }
- id, _ := result.LastInsertId()
- return &types.IdResp{Id: id}, nil
- }
|