add: user auth accomplished
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"juwan-backend/app/snowflake/rpc/snowflake"
|
||||
"juwan-backend/app/users/rpc/internal/models"
|
||||
"juwan-backend/app/users/rpc/internal/svc"
|
||||
"juwan-backend/app/users/rpc/pb"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
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 mustNewRandomNickname() string {
|
||||
bytes := make([]byte, 5)
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return "NewUser"
|
||||
}
|
||||
nickname := strings.Builder{}
|
||||
nickname.WriteString("user_")
|
||||
nickname.WriteString(hex.EncodeToString(bytes))
|
||||
return nickname.String()
|
||||
}
|
||||
|
||||
func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {
|
||||
// todo: add your logic here and delete this line
|
||||
if in.Phone == "" || in.Username == "" || in.Passwd == "" {
|
||||
logx.Error("invalid input")
|
||||
return nil, errors.New("invalid input")
|
||||
}
|
||||
|
||||
redisKey := fmt.Sprintf("vcode:%s:%s:%s", in.RequestId, "register", in.Email)
|
||||
vcode, err := l.svcCtx.RedisCluster.Get(l.ctx, redisKey).Result()
|
||||
logx.Infof("vcode:%s, err:%v", vcode, err)
|
||||
if err != nil {
|
||||
logx.Error("invalid verification code")
|
||||
return nil, errors.New("invalid verification code")
|
||||
}
|
||||
|
||||
code, err := strconv.ParseInt(vcode, 10, 32)
|
||||
if err != nil || int32(code) != in.Vcode {
|
||||
logx.Error("invalid verification code")
|
||||
return nil, errors.New("invalid verification code")
|
||||
}
|
||||
|
||||
resp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
|
||||
if err != nil {
|
||||
return nil, errors.New("generate user ID failed")
|
||||
}
|
||||
|
||||
user := models.Users{
|
||||
UserId: resp.Id,
|
||||
Username: in.Username,
|
||||
Nickname: mustNewRandomNickname(),
|
||||
Passwd: in.Passwd,
|
||||
Phone: in.Phone,
|
||||
Email: in.Email,
|
||||
RoleType: 0,
|
||||
IsVerified: false,
|
||||
}
|
||||
|
||||
_, err = l.svcCtx.UsersModelRW.Insert(l.ctx, &user)
|
||||
if err != nil {
|
||||
logx.Error("failed to create user: ", err)
|
||||
return nil, errors.New("failed to create user")
|
||||
}
|
||||
|
||||
return &pb.RegisterResp{
|
||||
Res: "user registered successfully",
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user