You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.3 KiB
86 lines
2.3 KiB
package logic
|
|
|
|
import (
|
|
"backend/usercenter/orm"
|
|
"backend/usercenter/rpc/internal/svc"
|
|
"backend/usercenter/rpc/pb/usercenter"
|
|
"backend/utils"
|
|
"context"
|
|
"errors"
|
|
"regexp"
|
|
"strconv"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type RegisterLogic struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
logx.Logger
|
|
}
|
|
|
|
func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
|
|
return &RegisterLogic{
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
Logger: logx.WithContext(ctx),
|
|
}
|
|
}
|
|
|
|
func (l *RegisterLogic) Register(in *usercenter.RegisterRequest) (*usercenter.RegisterResponse, error) {
|
|
// 1. 检查用户是否存在
|
|
user := new(orm.User)
|
|
res := l.svcCtx.UsercenterDB.First(user, "name = ?", in.Username)
|
|
// 有错误返回错误,找到数据返回找到
|
|
if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
|
|
return nil, errors.New(res.Error.Error())
|
|
}
|
|
if res.RowsAffected > 0 {
|
|
return nil, errors.New("用户已存在")
|
|
}
|
|
|
|
// 2. 检查手机号是否存在
|
|
res = l.svcCtx.UsercenterDB.First(user, "phone = ?", in.Mobile)
|
|
if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
|
|
return nil, errors.New(res.Error.Error())
|
|
}
|
|
if res.RowsAffected > 0 {
|
|
return nil, errors.New("手机号已存在")
|
|
}
|
|
// 3. 检查用户名是否符合要求
|
|
if len(in.Username) < 4 || len(in.Username) > 16 {
|
|
return nil, errors.New("用户名长度必须在4-16之间")
|
|
}
|
|
// 4. 检查密码是否符合要求
|
|
if len(in.Password) < 6 || len(in.Password) > 16 {
|
|
return nil, errors.New("密码长度必须在6-16之间")
|
|
}
|
|
// 5. 检查手机号是否符合要求
|
|
if len(in.Mobile) != 11 {
|
|
return nil, errors.New("手机号长度必须为11位")
|
|
}
|
|
// 6. 正则检查手机号
|
|
if !regexp.MustCompile(`^1[3-9]\d{9}$`).MatchString(in.Mobile) {
|
|
return nil, errors.New("手机号格式不正确")
|
|
}
|
|
// 检查完成,创建用户
|
|
// 密码加盐, utils.bcrypt.HashPassword
|
|
salt, err := utils.HashPassword(in.Password)
|
|
if err != nil {
|
|
return nil, errors.New(err.Error())
|
|
}
|
|
user.Name = in.Username
|
|
user.Phone = in.Mobile
|
|
user.Password = salt
|
|
|
|
res = l.svcCtx.UsercenterDB.Create(user)
|
|
if res.Error != nil {
|
|
return nil, errors.New(res.Error.Error())
|
|
}
|
|
// 创建成功,返回成功
|
|
return &usercenter.RegisterResponse{
|
|
UserId: strconv.FormatUint(uint64(user.ID), 10),
|
|
Message: "注册成功",
|
|
}, nil
|
|
}
|
|
|