Skip to content

Commit

Permalink
nil check in refreshHandler + refreshHandler code refactoring (#165)
Browse files Browse the repository at this point in the history
1) added a nil check in refreshHandler to prevent panic when token is nil, this is when there is no JWT in cookie

2) refactored code to new RefreshToken func, for ppl who like to refresh everytime in Authorization or every request

3) refactored code to new CheckIfTokenExpire func, for ppl who like to only check if token is expired in Authorization, mainly for SPA use, one way to refresh is to only refresh on application load
  • Loading branch information
kingcw authored and appleboy committed Sep 13, 2018
1 parent bfaf3ee commit 59e38b5
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,14 +438,20 @@ func (mw *GinJWTMiddleware) signedString(token *jwt.Token) (string, error) {
// Shall be put under an endpoint that is using the GinJWTMiddleware.
// Reply will be of the form {"token": "TOKEN"}.
func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
token, _ := mw.ParseToken(c)
claims := token.Claims.(jwt.MapClaims)
tokenString, expire, err := mw.RefreshToken(c)
if err != nil {
mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
return
}

origIat := int64(claims["orig_iat"].(float64))
mw.RefreshResponse(c, http.StatusOK, tokenString, expire)
}

if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() {
mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
return
// RefreshToken refresh token and check if token is expired
func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) {
claims, err := mw.CheckIfTokenExpire(c)
if err != nil {
return "", time.Now(), ErrExpiredToken
}

// Create the token
Expand All @@ -462,8 +468,7 @@ func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
tokenString, err := mw.signedString(newToken)

if err != nil {
mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrFailedTokenCreation, c))
return
return "", time.Now(), err
}

// set cookie
Expand All @@ -480,7 +485,25 @@ func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
)
}

mw.RefreshResponse(c, http.StatusOK, tokenString, expire)
return tokenString, expire, nil
}

// CheckIfTokenExpire check if token expire
func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error) {
token, err := mw.ParseToken(c)
if err != nil {
return nil, err
}

claims := token.Claims.(jwt.MapClaims)

origIat := int64(claims["orig_iat"].(float64))

if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() {
return nil, ErrExpiredToken
}

return claims, nil
}

// TokenGenerator method that clients can use to get a jwt token.
Expand Down

0 comments on commit 59e38b5

Please sign in to comment.