jwt 认证

This commit is contained in:
eson
2023-06-06 20:08:32 +08:00
parent ab9df9bc42
commit 48be41f64b
11 changed files with 192 additions and 44 deletions

View File

@@ -2,6 +2,7 @@ package logic
import (
"context"
"log"
"fusenapi/home-user-auth/internal/svc"
"fusenapi/home-user-auth/internal/types"
@@ -29,6 +30,9 @@ func NewUserBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Use
func (l *UserBasicInfoLogic) UserBasicInfo(req *types.Request, userinfo *auth.UserInfo) (resp *types.Response) {
// 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error")
resp = &types.Response{}
// u := l.ctx.Value("userid").(int64)
u := l.ctx.Value("userid")
log.Println(u)
if userinfo.UserId == 0 {
resp = &types.Response{

View File

@@ -2,6 +2,7 @@ package logic
import (
"context"
"time"
"fusenapi/home-user-auth/internal/svc"
"fusenapi/home-user-auth/internal/types"
@@ -26,30 +27,44 @@ func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLog
}
}
func (l *UserLoginLogic) getJwtToken(secretKey string, iat, seconds, userId int64) (string, error) {
func (l *UserLoginLogic) genJwtToken(accessSecret string, accessExpire, nowSec, userid int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
claims["userId"] = userId
claims["exp"] = nowSec + accessExpire
claims["iat"] = nowSec
claims["userid"] = userid
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
return token.SignedString([]byte(accessSecret))
}
func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin) (resp *types.Response) {
func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin) (resp *types.Response, jwtToken string) {
// 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error")
resp = &types.Response{}
userModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOneByEmail(l.ctx, req.Name)
// log.Printf("%t %t %v", err, model.ErrNotFound, err == model.ErrNotFound)
if err == model.ErrNotFound {
logx.Error(err)
resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error())
return resp
return resp, jwtToken
}
// jwt 生成
nowSec := time.Now().Unix()
jwtToken, err = l.genJwtToken(l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, userModel.Id)
if err != nil {
logx.Error(err)
resp.SetStatus(basic.CodeUnAuth)
return resp, jwtToken
}
data := &types.DataUserLogin{
Token: userModel.PasswordResetToken.String,
Token: userModel.PasswordResetToken.String,
JwtToken: jwtToken,
}
resp.SetStatus(basic.CodeOK, data)
return resp
return resp, jwtToken
}