fusenapi/server/home-user-auth/internal/logic/userloginlogic.go

71 lines
2.1 KiB
Go
Raw Normal View History

2023-06-01 10:35:09 +00:00
package logic
import (
"context"
2023-06-20 09:29:02 +00:00
"errors"
2023-06-06 12:08:32 +00:00
"time"
2023-06-01 10:35:09 +00:00
2023-06-15 08:08:43 +00:00
"fusenapi/model/gmodel"
2023-06-08 02:51:56 +00:00
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
2023-06-12 07:17:42 +00:00
"fusenapi/utils/auth"
2023-06-05 09:56:55 +00:00
"fusenapi/utils/basic"
2023-06-01 10:35:09 +00:00
"github.com/zeromicro/go-zero/core/logx"
2023-06-15 08:08:43 +00:00
"gorm.io/gorm"
2023-06-01 10:35:09 +00:00
)
type UserLoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
return &UserLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
2023-06-12 09:28:49 +00:00
func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin) (resp *basic.Response, jwtToken string) {
2023-06-12 07:17:42 +00:00
// 创建一个 FsUserModel 对象 m 并实例化之,该对象用于操作 MySQL 数据库中的用户数据表。
2023-06-15 08:08:43 +00:00
m := gmodel.NewFsUserModel(l.svcCtx.MysqlConn)
2023-06-12 07:17:42 +00:00
2023-06-15 08:08:43 +00:00
// 在用户数据表中根据登录名(email)查找用户记录,并返回 UserModel 类型的结构体对象 userModel。
user, err := m.FindUserByEmail(l.ctx, req.Name)
2023-06-20 09:29:02 +00:00
if errors.Is(err, gorm.ErrRecordNotFound) {
2023-06-15 08:08:43 +00:00
return resp.SetStatus(basic.CodeEmailNotFoundErr), ""
2023-06-01 10:35:09 +00:00
}
2023-06-06 12:08:32 +00:00
2023-06-12 07:17:42 +00:00
// 如果在用户数据表中找到了登录名匹配的用户记录,则判断密码是否匹配。
2023-06-15 08:08:43 +00:00
if *user.PasswordHash != req.Password {
2023-06-07 10:30:58 +00:00
logx.Info("密码错误")
2023-06-15 08:08:43 +00:00
return resp.SetStatus(basic.CodePasswordErr), jwtToken
2023-06-07 10:30:58 +00:00
}
2023-06-12 07:17:42 +00:00
// 如果密码匹配,则生成 JWT Token。
2023-06-06 12:08:32 +00:00
nowSec := time.Now().Unix()
2023-06-15 08:08:43 +00:00
jwtToken, err = auth.GenerateJwtToken(&l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, user.Id, 0)
2023-06-12 07:17:42 +00:00
// 如果生成 JWT Token 失败,则抛出错误并返回未认证的状态码。
2023-06-06 12:08:32 +00:00
if err != nil {
logx.Error(err)
2023-06-07 03:57:04 +00:00
return resp.SetStatus(basic.CodeUnAuth), jwtToken
2023-06-06 12:08:32 +00:00
}
2023-06-12 07:17:42 +00:00
// 如果更新 VerificationToken 字段失败,则返回未认证的状态码。
2023-06-07 10:30:58 +00:00
if err != nil {
return resp.SetStatus(basic.CodeUnAuth), jwtToken
}
2023-06-12 07:17:42 +00:00
// 构造 DataUserLogin 类型的数据对象 data 并设置其属性值为生成的 JWT Token。
2023-06-05 09:56:55 +00:00
data := &types.DataUserLogin{
2023-06-07 10:30:58 +00:00
Token: jwtToken,
2023-06-01 10:35:09 +00:00
}
2023-06-06 12:08:32 +00:00
2023-06-12 07:17:42 +00:00
// 返回认证成功的状态码以及数据对象 data 和 JWT Token。
2023-06-07 03:57:04 +00:00
return resp.SetStatus(basic.CodeOK, data), jwtToken
2023-06-01 10:35:09 +00:00
}