94 lines
2.7 KiB
Go
94 lines
2.7 KiB
Go
package logic
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"fusenapi/utils/auth"
|
|
"fusenapi/utils/basic"
|
|
"net/http"
|
|
"time"
|
|
|
|
"context"
|
|
|
|
"fusenapi/server/auth/internal/svc"
|
|
"fusenapi/server/auth/internal/types"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type UserLoginLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
|
|
token string
|
|
}
|
|
|
|
func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
|
|
return &UserLoginLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
// 处理进入前逻辑w,r
|
|
// func (l *UserLoginLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
|
// }
|
|
|
|
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
|
|
func (l *UserLoginLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
|
if l.token != "" {
|
|
w.Header().Add("Authorization", fmt.Sprintf("Bearer %s", l.token))
|
|
}
|
|
|
|
httpx.OkJsonCtx(r.Context(), w, resp)
|
|
}
|
|
|
|
func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin, userinfo *auth.UserInfo) (resp *basic.Response) {
|
|
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
|
// userinfo 传入值时, 一定不为null
|
|
|
|
// 创建一个 FsUserModel 对象 m 并实例化之,该对象用于操作 MySQL 数据库中的用户数据表。
|
|
m := l.svcCtx.AllModels.FsUser
|
|
|
|
// 在用户数据表中根据登录名(email)查找用户记录,并返回 UserModel 类型的结构体对象 userModel。
|
|
user, err := m.FindUserByEmail(l.ctx, req.Email)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return resp.SetStatus(basic.CodeEmailNotFoundErr)
|
|
}
|
|
|
|
// 如果在用户数据表中找到了登录名匹配的用户记录,则判断密码是否匹配。
|
|
if *user.PasswordHash != req.Password {
|
|
logx.Info("密码错误")
|
|
return resp.SetStatus(basic.CodePasswordErr)
|
|
}
|
|
|
|
// 如果密码匹配,则生成 JWT Token。
|
|
nowSec := time.Now().Unix()
|
|
jwtToken, err := auth.GenerateJwtToken(&l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, user.Id, 0)
|
|
|
|
// 如果生成 JWT Token 失败,则抛出错误并返回未认证的状态码。
|
|
if err != nil {
|
|
logx.Error(err)
|
|
return resp.SetStatus(basic.CodeUnAuth)
|
|
}
|
|
|
|
// 如果更新 VerificationToken 字段失败,则返回未认证的状态码。
|
|
if err != nil {
|
|
return resp.SetStatus(basic.CodeUnAuth)
|
|
}
|
|
|
|
// 构造 DataUserLogin 类型的数据对象 data 并设置其属性值为生成的 JWT Token。
|
|
data := &types.DataUserLogin{
|
|
Token: jwtToken,
|
|
}
|
|
|
|
l.token = jwtToken
|
|
|
|
// 返回认证成功的状态码以及数据对象 data 和 JWT Token。
|
|
return resp.SetStatus(basic.CodeOK, data)
|
|
}
|