63 lines
1.5 KiB
Go
63 lines
1.5 KiB
Go
package authlogic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/zeromicro/go-zero/core/stores/redis"
|
|
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
|
jwtx "tianyuan-api/pkg/jwt"
|
|
|
|
"tianyuan-api/apps/user/internal/svc"
|
|
"tianyuan-api/apps/user/user"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type PhoneLoginUserLogic struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
logx.Logger
|
|
}
|
|
|
|
func NewPhoneLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PhoneLoginUserLogic {
|
|
return &PhoneLoginUserLogic{
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
Logger: logx.WithContext(ctx),
|
|
}
|
|
}
|
|
|
|
// 手机登录接口
|
|
func (l *PhoneLoginUserLogic) PhoneLoginUser(in *user.PhoneLoginReq) (*user.LoginResp, error) {
|
|
// 从 Redis 获取验证码
|
|
savedCode, err := l.svcCtx.Redis.Get(fmt.Sprintf("login:%s", in.Phone))
|
|
if err != nil {
|
|
if errors.Is(err, redis.Nil) {
|
|
return nil, errors.New("验证码已过期")
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
// 验证码不匹配
|
|
if savedCode != in.Code {
|
|
return nil, errors.New("验证码不正确")
|
|
}
|
|
// 查询用户是否存在,如果不存在则注册新用户
|
|
users, err := l.svcCtx.UserModel.FindOneByPhone(l.ctx, in.Phone)
|
|
if errors.Is(err, sqlx.ErrNotFound) {
|
|
return nil, errors.New("手机号未注册")
|
|
} else if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
token, err := jwtx.GenerateJwtToken(users.Id, l.svcCtx.Config.AuthJWT.AccessSecret, l.svcCtx.Config.AuthJWT.AccessExpire)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &user.LoginResp{
|
|
Token: token,
|
|
}, nil
|
|
}
|