fixed JWT valide error whent get user by id failed

pull/363/head
Michael Li 1 year ago
parent 927e0aa6de
commit 51fd9724b9
No known key found for this signature in database

@ -25,7 +25,6 @@ func JWT() gin.HandlerFunc {
token = s token = s
} else { } else {
token = c.GetHeader("Authorization") token = c.GetHeader("Authorization")
// 验证前端传过来的token格式不为空开头为Bearer // 验证前端传过来的token格式不为空开头为Bearer
if token == "" || !strings.HasPrefix(token, "Bearer ") { if token == "" || !strings.HasPrefix(token, "Bearer ") {
response := app.NewResponse(c) response := app.NewResponse(c)
@ -33,47 +32,41 @@ func JWT() gin.HandlerFunc {
c.Abort() c.Abort()
return return
} }
// 验证通过提取有效部分除去Bearer) // 验证通过提取有效部分除去Bearer)
token = token[7:] token = token[7:]
} }
if token == "" { if token != "" {
ecode = xerror.InvalidParams if claims, err := app.ParseToken(token); err == nil {
// 加载用户信息
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 { } else {
claims, err := app.ParseToken(token)
if err != nil {
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = xerror.UnauthorizedTokenTimeout ecode = xerror.UnauthorizedTokenTimeout
default:
ecode = xerror.UnauthorizedTokenError
} }
} else {
c.Set("UID", claims.UID)
c.Set("USERNAME", claims.Username)
// 加载用户信息
user, err := ums.GetUserByID(claims.UID)
if err == nil {
c.Set("USER", user)
} else { } else {
ecode = xerror.UnauthorizedAuthNotExist ecode = xerror.UnauthorizedAuthNotExist
} }
} else {
// 强制下线机制 switch err.(*jwt.ValidationError).Errors {
if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer { case jwt.ValidationErrorExpired:
ecode = xerror.UnauthorizedTokenTimeout ecode = xerror.UnauthorizedTokenTimeout
default:
ecode = xerror.UnauthorizedTokenError
} }
} }
} else {
ecode = xerror.InvalidParams
} }
if ecode != xerror.Success { if ecode != xerror.Success {
response := app.NewResponse(c) response := app.NewResponse(c)
response.ToErrorResponse(ecode) response.ToErrorResponse(ecode)
c.Abort() c.Abort()
return return
} }
c.Next() c.Next()
} }
} }
@ -94,11 +87,11 @@ func JwtLoose() gin.HandlerFunc {
} }
if len(token) > 0 { if len(token) > 0 {
if claims, err := app.ParseToken(token); err == nil { if claims, err := app.ParseToken(token); err == nil {
c.Set("UID", claims.UID)
c.Set("USERNAME", claims.Username)
// 加载用户信息 // 加载用户信息
user, err := ums.GetUserByID(claims.UID) user, err := ums.GetUserByID(claims.UID)
if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer { if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer {
c.Set("UID", claims.UID)
c.Set("USERNAME", claims.Username)
c.Set("USER", user) c.Set("USER", user)
} }
} }

Loading…
Cancel
Save