1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

JWT BeforeFunc, SuccessHandler & ErrorHandler

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2018-06-28 18:13:02 -07:00
parent 56091a4186
commit 61084e242e
2 changed files with 29 additions and 1 deletions

View File

@ -16,6 +16,15 @@ type (
// Skipper defines a function to skip middleware.
Skipper Skipper
// BeforeFunc defines a function which is executed just before the middleware.
BeforeFunc BeforeFunc
// SuccessHandler defines a function which is executed for a valid token.
SuccessHandler JWTSuccessHandler
// ErrorHandler defines a function which is executed for an invalid token.
ErrorHandler JWTErrorHandler
// Signing key to validate token.
// Required.
SigningKey interface{}
@ -48,6 +57,12 @@ type (
keyFunc jwt.Keyfunc
}
// JWTSuccessHandler defines a function which is executed for a valid token.
JWTSuccessHandler func(echo.Context)
// JWTErrorHandler defines a function which is executed for an invalid token.
JWTErrorHandler func(echo.Context, echo.HandlerFunc) error
jwtExtractor func(echo.Context) (string, error)
)
@ -137,6 +152,10 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
return next(c)
}
if config.BeforeFunc != nil {
config.BeforeFunc(c)
}
auth, err := extractor(c)
if err != nil {
return err
@ -153,8 +172,14 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
if err == nil && token.Valid {
// Store user information from token into context.
c.Set(config.ContextKey, token)
if config.SuccessHandler != nil {
config.SuccessHandler(c)
}
return next(c)
}
if config.ErrorHandler != nil {
return config.ErrorHandler(c, next)
}
return &echo.HTTPError{
Code: ErrJWTInvalid.Code,
Message: ErrJWTInvalid.Message,

View File

@ -11,7 +11,10 @@ import (
type (
// Skipper defines a function to skip middleware. Returning true skips processing
// the middleware.
Skipper func(c echo.Context) bool
Skipper func(echo.Context) bool
// BeforeFunc defines a function which is executed just before the middleware.
BeforeFunc func(echo.Context)
)
func captureTokens(pattern *regexp.Regexp, input string) *strings.Replacer {