Skip to content

Commit

Permalink
JWT BeforeFunc, SuccessHandler & ErrorHandler
Browse files Browse the repository at this point in the history
Signed-off-by: Vishal Rana <vr@labstack.com>
  • Loading branch information
vishr committed Jun 29, 2018
1 parent 56091a4 commit 61084e2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
25 changes: 25 additions & 0 deletions middleware/jwt.go
Expand Up @@ -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{}
Expand Down Expand Up @@ -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)
)

Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
5 changes: 4 additions & 1 deletion middleware/middleware.go
Expand Up @@ -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 {
Expand Down

0 comments on commit 61084e2

Please sign in to comment.