Skip to content

Commit

Permalink
feat: set timeout dynamically - Add TimeoutFunc (#337)
Browse files Browse the repository at this point in the history
closes #313
  • Loading branch information
a5r0n authored Aug 30, 2024
1 parent 2b1dbef commit 19d6e4c
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ type GinJWTMiddleware struct {

// Duration that a jwt token is valid. Optional, defaults to one hour.
Timeout time.Duration
// Callback function that will override the default timeout duration.
TimeoutFunc func(data interface{}) time.Duration

// This field allows clients to refresh their token until MaxRefresh has passed.
// Note that clients can refresh their token in the last moment of MaxRefresh.
Expand Down Expand Up @@ -313,6 +315,12 @@ func (mw *GinJWTMiddleware) MiddlewareInit() error {
mw.Timeout = time.Hour
}

if mw.TimeoutFunc == nil {
mw.TimeoutFunc = func(data interface{}) time.Duration {
return mw.Timeout
}
}

if mw.TimeFunc == nil {
mw.TimeFunc = time.Now
}
Expand Down Expand Up @@ -508,7 +516,7 @@ func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
}
}

expire := mw.TimeFunc().Add(mw.Timeout)
expire := mw.TimeFunc().Add(mw.TimeoutFunc(claims))
claims["exp"] = expire.Unix()
claims["orig_iat"] = mw.TimeFunc().Unix()
tokenString, err := mw.signedString(token)
Expand Down Expand Up @@ -583,7 +591,7 @@ func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, err
newClaims[key] = claims[key]
}

expire := mw.TimeFunc().Add(mw.Timeout)
expire := mw.TimeFunc().Add(mw.TimeoutFunc(claims))
newClaims["exp"] = expire.Unix()
newClaims["orig_iat"] = mw.TimeFunc().Unix()
tokenString, err := mw.signedString(newToken)
Expand Down Expand Up @@ -633,7 +641,7 @@ func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time,
}
}

expire := mw.TimeFunc().Add(mw.Timeout)
expire := mw.TimeFunc().Add(mw.TimeoutFunc(claims))
claims["exp"] = expire.Unix()
claims["orig_iat"] = mw.TimeFunc().Unix()
tokenString, err := mw.signedString(token)
Expand Down

0 comments on commit 19d6e4c

Please sign in to comment.