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.
88 lines
2.1 KiB
88 lines
2.1 KiB
package user
|
|
|
|
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 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.CreateUserRequest) (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)
|
|
}
|
|
|
|
// 密码加密(简单MD5,实际项目应使用bcrypt等更安全的加密)
|
|
encryptedPassword := fmt.Sprintf("%x", md5.Sum([]byte(req.Password)))
|
|
|
|
// 设置角色(默认为 user)
|
|
role := req.Role
|
|
if role == "" {
|
|
role = model.RoleUser
|
|
}
|
|
|
|
// 创建用户模型
|
|
user := &model.User{
|
|
Username: req.Username,
|
|
Email: req.Email,
|
|
Password: encryptedPassword,
|
|
Phone: req.Phone,
|
|
Role: role,
|
|
Source: model.SourceManual,
|
|
Remark: req.Remark,
|
|
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,
|
|
Role: user.Role,
|
|
Source: user.Source,
|
|
Remark: user.Remark,
|
|
Status: int(user.Status),
|
|
CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
|
|
UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|