init: init refactor
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"sundynix-micro-go/app/user/model"
|
||||
"sundynix-micro-go/app/user/rpc/internal/svc"
|
||||
"sundynix-micro-go/app/user/rpc/user"
|
||||
"sundynix-micro-go/common/utils/hash"
|
||||
"sundynix-micro-go/common/utils/uniqueid"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CreateUserLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logx.Logger
|
||||
}
|
||||
|
||||
func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
|
||||
return &CreateUserLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logx.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
func (l *CreateUserLogic) CreateUser(in *user.CreateUserReq) (*user.CreateUserResp, error) {
|
||||
// 如果有OpenID,先检查是否存在
|
||||
if in.OpenId != "" {
|
||||
var existing model.SundynixUser
|
||||
err := l.svcCtx.DB.Where("open_id = ?", in.OpenId).First(&existing).Error
|
||||
if err == nil {
|
||||
// 用户已存在,更新session_key
|
||||
if in.SessionKey != "" {
|
||||
l.svcCtx.DB.Model(&existing).UpdateColumn("session_key", in.SessionKey)
|
||||
}
|
||||
return &user.CreateUserResp{
|
||||
User: convertUserToProto(&existing),
|
||||
}, nil
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorf("查询用户失败: %v", err)
|
||||
return nil, status.Error(codes.Internal, "查询用户失败")
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新用户
|
||||
name := in.Name
|
||||
if name == "" {
|
||||
name = uniqueid.GenerateName("用户")
|
||||
}
|
||||
|
||||
newUser := model.SundynixUser{
|
||||
Name: name,
|
||||
OpenID: in.OpenId,
|
||||
SessionKey: in.SessionKey,
|
||||
ClientID: in.ClientId,
|
||||
Phone: in.Phone,
|
||||
}
|
||||
|
||||
// 如果有密码则加密
|
||||
if in.Phone != "" {
|
||||
newUser.Password = hash.BcryptHash(in.Phone) // 默认密码为手机号
|
||||
}
|
||||
|
||||
if err := l.svcCtx.DB.Create(&newUser).Error; err != nil {
|
||||
l.Errorf("创建用户失败: %v", err)
|
||||
return nil, status.Error(codes.Internal, "创建用户失败")
|
||||
}
|
||||
|
||||
return &user.CreateUserResp{
|
||||
User: convertUserToProto(&newUser),
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user