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.
61 lines
1.6 KiB
61 lines
1.6 KiB
package logic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"backend/usercenter/orm"
|
|
"backend/usercenter/rpc/internal/svc"
|
|
"backend/usercenter/rpc/pb/usercenter"
|
|
"backend/utils"
|
|
|
|
"github.com/spf13/cast"
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type LoginLogic struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
logx.Logger
|
|
}
|
|
|
|
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
|
|
return &LoginLogic{
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
Logger: logx.WithContext(ctx),
|
|
}
|
|
}
|
|
|
|
func (l *LoginLogic) Login(in *usercenter.LoginRequest) (*usercenter.LoginResponse, error) {
|
|
// 1. 验证用户是否存在,支持用户名和手机号登录
|
|
user := new(orm.User)
|
|
result := l.svcCtx.UsercenterDB.Where("name = ? OR phone = ?", in.Identity, in.Identity).First(&user)
|
|
if result.Error != nil && result.Error != gorm.ErrRecordNotFound {
|
|
return nil, result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return nil, errors.New("用户不存在")
|
|
}
|
|
|
|
// 2. 验证密码,使用 utils.bcrypt.CheckPassword 工具类进行比较
|
|
if !utils.CheckPassword(user.Password, in.Password) {
|
|
return nil, errors.New("密码错误")
|
|
}
|
|
|
|
// 3. 生成token,使用 utils.GenerateToken 工具类生成
|
|
jwtUtil := utils.NewJWTUtil(l.svcCtx.Config.AuthRpc.AccessSecret, l.svcCtx.Config.AuthRpc.AccessExpire, l.svcCtx.RedisClient, l.svcCtx.Config.TkStore)
|
|
token, err := jwtUtil.GenerateToken(l.ctx, cast.ToInt64(user.ID), user.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 4. 返回token
|
|
|
|
return &usercenter.LoginResponse{
|
|
UserId: cast.ToString(user.ID),
|
|
Token: token,
|
|
Message: "登录成功",
|
|
}, nil
|
|
}
|
|
|