Files
ocean/user/internal/logic/registerlogic.go
2025-05-22 19:39:08 +08:00

91 lines
2.3 KiB
Go

package logic
import (
"context"
"database/sql"
"godemo/user/internal/model"
"godemo/user/internal/svc"
"godemo/user/user"
"time"
"github.com/lib/pq"
"github.com/zeromicro/go-zero/core/logx"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
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 *user.RegisterRequest) (*user.RegisterResponse, error) {
// 1. 检查用户名是否已存在
var existingUser model.User
err := l.svcCtx.DB.Get(&existingUser, "SELECT * FROM users WHERE username = $1", in.Username)
if err == nil {
// 用户名已存在
return nil, status.Error(codes.AlreadyExists, "用户名已存在")
}
// 2. 加密密码
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
if err != nil {
// 密码加密失败
return nil, status.Error(codes.Internal, err.Error())
}
// 3. 转换 email 为 sql.NullString
var email sql.NullString
if in.Email != "" {
email = sql.NullString{
String: in.Email,
Valid: true,
}
} else {
email = sql.NullString{Valid: false}
}
// 4. 保存新用户到数据库
userModel := model.User{
Username: in.Username,
PasswordHash: string(hashedPassword),
Email: email, // 使用 sql.NullString 类型存储 email
Roles: []string{"user"}, // 默认角色为 "user"
CreatedAt: time.Now(), // 当前时间戳
}
// 执行插入数据库操作
_, err = l.svcCtx.DB.Exec(
"INSERT INTO users (username, password_hash, email, roles, created_at) VALUES ($1, $2, $3, $4, $5)",
userModel.Username,
userModel.PasswordHash,
userModel.Email,
pq.Array(userModel.Roles), // pq.Array 用于处理 PostgreSQL 数组类型
userModel.CreatedAt,
)
if err != nil {
// 数据库插入失败
return nil, status.Error(codes.Internal, err.Error())
}
// 获取插入的记录的 UserId
l.svcCtx.DB.Get(&existingUser, "SELECT * FROM users WHERE username = $1", in.Username)
// 5. 返回成功响应
return &user.RegisterResponse{
UserId: existingUser.UserId, // 将 UserId 转换为字符串
}, nil
}