Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: set timeout dynamically - Add TimeoutFunc #337

Merged
merged 1 commit into from
Aug 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading