1
0
mirror of https://github.com/labstack/echo.git synced 2025-12-05 23:08:17 +02:00

add a custom error handler to key-auth middleware (#1847)

* add a custom error handler to key-auth middleware
This commit is contained in:
王瑞华
2021-05-09 03:25:11 +08:00
committed by GitHub
parent 76f186ad3b
commit 7256cb2274
2 changed files with 224 additions and 51 deletions

View File

@@ -30,12 +30,19 @@ type (
// Validator is a function to validate key.
// Required.
Validator KeyAuthValidator
// ErrorHandler defines a function which is executed for an invalid key.
// It may be used to define a custom error.
ErrorHandler KeyAuthErrorHandler
}
// KeyAuthValidator defines a function to validate KeyAuth credentials.
KeyAuthValidator func(string, echo.Context) (bool, error)
keyExtractor func(echo.Context) (string, error)
// KeyAuthErrorHandler defines a function which is executed for an invalid key.
KeyAuthErrorHandler func(error, echo.Context) error
)
var (
@@ -95,10 +102,16 @@ func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc {
// Extract and verify key
key, err := extractor(c)
if err != nil {
if config.ErrorHandler != nil {
return config.ErrorHandler(err, c)
}
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
valid, err := config.Validator(key, c)
if err != nil {
if config.ErrorHandler != nil {
return config.ErrorHandler(err, c)
}
return &echo.HTTPError{
Code: http.StatusUnauthorized,
Message: "invalid key",