From 51fd9724b96bbc8cc64405b36a5fd7ae69b7a52c Mon Sep 17 00:00:00 2001 From: Michael Li Date: Tue, 22 Aug 2023 21:35:20 +0800 Subject: [PATCH] fixed JWT valide error whent get user by id failed --- internal/servants/chain/jwt.go | 47 +++++++++++++++------------------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/internal/servants/chain/jwt.go b/internal/servants/chain/jwt.go index efdf2231..ae96d550 100644 --- a/internal/servants/chain/jwt.go +++ b/internal/servants/chain/jwt.go @@ -25,7 +25,6 @@ func JWT() gin.HandlerFunc { token = s } else { token = c.GetHeader("Authorization") - // 验证前端传过来的token格式,不为空,开头为Bearer if token == "" || !strings.HasPrefix(token, "Bearer ") { response := app.NewResponse(c) @@ -33,47 +32,41 @@ func JWT() gin.HandlerFunc { c.Abort() return } - // 验证通过,提取有效部分(除去Bearer) token = token[7:] } - if token == "" { - ecode = xerror.InvalidParams - } else { - claims, err := app.ParseToken(token) - if err != nil { - switch err.(*jwt.ValidationError).Errors { - case jwt.ValidationErrorExpired: - ecode = xerror.UnauthorizedTokenTimeout - default: - ecode = xerror.UnauthorizedTokenError - } - } else { - c.Set("UID", claims.UID) - c.Set("USERNAME", claims.Username) - + if token != "" { + if claims, err := app.ParseToken(token); err == nil { // 加载用户信息 - user, err := ums.GetUserByID(claims.UID) - if err == nil { - c.Set("USER", user) + if user, err := ums.GetUserByID(claims.UID); err == nil { + // 强制下线机制 + if (conf.JWTSetting.Issuer + ":" + user.Salt) == claims.Issuer { + c.Set("USER", user) + c.Set("UID", claims.UID) + c.Set("USERNAME", claims.Username) + } else { + ecode = xerror.UnauthorizedTokenTimeout + } } else { ecode = xerror.UnauthorizedAuthNotExist } - - // 强制下线机制 - if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer { + } else { + switch err.(*jwt.ValidationError).Errors { + case jwt.ValidationErrorExpired: ecode = xerror.UnauthorizedTokenTimeout + default: + ecode = xerror.UnauthorizedTokenError } } + } else { + ecode = xerror.InvalidParams } - if ecode != xerror.Success { response := app.NewResponse(c) response.ToErrorResponse(ecode) c.Abort() return } - c.Next() } } @@ -94,11 +87,11 @@ func JwtLoose() gin.HandlerFunc { } if len(token) > 0 { if claims, err := app.ParseToken(token); err == nil { - c.Set("UID", claims.UID) - c.Set("USERNAME", claims.Username) // 加载用户信息 user, err := ums.GetUserByID(claims.UID) if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer { + c.Set("UID", claims.UID) + c.Set("USERNAME", claims.Username) c.Set("USER", user) } }