Skip to content

Commit

Permalink
fixed JWT valide error whent get user by id failed
Browse files Browse the repository at this point in the history
  • Loading branch information
alimy committed Aug 22, 2023
1 parent 927e0aa commit 51fd972
Showing 1 changed file with 20 additions and 27 deletions.
47 changes: 20 additions & 27 deletions internal/servants/chain/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,55 +25,48 @@ func JWT() gin.HandlerFunc {
token = s
} else {
token = c.GetHeader("Authorization")

// 验证前端传过来的token格式,不为空,开头为Bearer
if token == "" || !strings.HasPrefix(token, "Bearer ") {
response := app.NewResponse(c)
response.ToErrorResponse(xerror.UnauthorizedTokenError)
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()
}
}
Expand All @@ -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)
}
}
Expand Down

0 comments on commit 51fd972

Please sign in to comment.