Skip to content

Commit 61084e2

Browse files
committed
JWT BeforeFunc, SuccessHandler & ErrorHandler
Signed-off-by: Vishal Rana <[email protected]>
1 parent 56091a4 commit 61084e2

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

middleware/jwt.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@ type (
1616
// Skipper defines a function to skip middleware.
1717
Skipper Skipper
1818

19+
// BeforeFunc defines a function which is executed just before the middleware.
20+
BeforeFunc BeforeFunc
21+
22+
// SuccessHandler defines a function which is executed for a valid token.
23+
SuccessHandler JWTSuccessHandler
24+
25+
// ErrorHandler defines a function which is executed for an invalid token.
26+
ErrorHandler JWTErrorHandler
27+
1928
// Signing key to validate token.
2029
// Required.
2130
SigningKey interface{}
@@ -48,6 +57,12 @@ type (
4857
keyFunc jwt.Keyfunc
4958
}
5059

60+
// JWTSuccessHandler defines a function which is executed for a valid token.
61+
JWTSuccessHandler func(echo.Context)
62+
63+
// JWTErrorHandler defines a function which is executed for an invalid token.
64+
JWTErrorHandler func(echo.Context, echo.HandlerFunc) error
65+
5166
jwtExtractor func(echo.Context) (string, error)
5267
)
5368

@@ -137,6 +152,10 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
137152
return next(c)
138153
}
139154

155+
if config.BeforeFunc != nil {
156+
config.BeforeFunc(c)
157+
}
158+
140159
auth, err := extractor(c)
141160
if err != nil {
142161
return err
@@ -153,8 +172,14 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
153172
if err == nil && token.Valid {
154173
// Store user information from token into context.
155174
c.Set(config.ContextKey, token)
175+
if config.SuccessHandler != nil {
176+
config.SuccessHandler(c)
177+
}
156178
return next(c)
157179
}
180+
if config.ErrorHandler != nil {
181+
return config.ErrorHandler(c, next)
182+
}
158183
return &echo.HTTPError{
159184
Code: ErrJWTInvalid.Code,
160185
Message: ErrJWTInvalid.Message,

middleware/middleware.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ import (
1111
type (
1212
// Skipper defines a function to skip middleware. Returning true skips processing
1313
// the middleware.
14-
Skipper func(c echo.Context) bool
14+
Skipper func(echo.Context) bool
15+
16+
// BeforeFunc defines a function which is executed just before the middleware.
17+
BeforeFunc func(echo.Context)
1518
)
1619

1720
func captureTokens(pattern *regexp.Regexp, input string) *strings.Replacer {

0 commit comments

Comments
 (0)