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.
77 lines
1.9 KiB
77 lines
1.9 KiB
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"fmt"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type RegisterLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 用户注册
|
|
func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
|
|
return &RegisterLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *RegisterLogic) Register(req *types.RegisterRequest) (resp *types.UserInfo, err error) {
|
|
// 检查邮箱是否已存在
|
|
_, err = model.FindOneByEmail(l.ctx, l.svcCtx.DB, req.Email)
|
|
if err == nil {
|
|
return nil, fmt.Errorf("邮箱已被注册")
|
|
}
|
|
if err != model.ErrNotFound {
|
|
return nil, fmt.Errorf("检查邮箱失败: %v", err)
|
|
}
|
|
|
|
// 创建用户模型
|
|
user := &model.User{
|
|
Username: req.Username,
|
|
Email: req.Email,
|
|
Password: fmt.Sprintf("%x", md5.Sum([]byte(req.Password))), // 密码加密
|
|
Phone: req.Phone,
|
|
Status: 1, // 默认正常状态
|
|
}
|
|
|
|
// 插入数据库
|
|
id, err := model.Insert(l.ctx, l.svcCtx.DB, user)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("创建用户失败: %v", err)
|
|
}
|
|
|
|
// 查询创建的用户
|
|
user, err = model.FindOne(l.ctx, l.svcCtx.DB, id)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("查询用户失败: %v", err)
|
|
}
|
|
|
|
// 返回用户信息(不返回密码)
|
|
resp = &types.UserInfo{
|
|
Id: user.Id,
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
Phone: user.Phone,
|
|
Status: int(user.Status),
|
|
CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
|
|
UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
|
|
}
|
|
|
|
// 返回 Token 在响应头中(通过中间件处理)
|
|
// 临时方案:将 token 放入响应 Data 中
|
|
l.Infof("注册成功,userId=%d", user.Id)
|
|
|
|
return resp, nil
|
|
}
|
|
|