-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpath_auth.go
96 lines (80 loc) · 2.31 KB
/
path_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package echo_middleware_path_auth
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"net/http"
)
type (
// PathAuthConfig defines the config for PathAuth middleware.
PathAuthConfig struct {
// Skipper defines a function to skip middleware.
Skipper middleware.Skipper
// Validator is a function to validate key.
// Required.
Validator PathAuthValidator
Param string
}
// PathAuthValidator defines a function to validate PathAuth credentials.
PathAuthValidator func(auth string, c echo.Context) (bool, error)
)
var (
// DefaultKeyAuthConfig is the default PathAuth middleware config.
DefaultKeyAuthConfig = PathAuthConfig{
Skipper: middleware.DefaultSkipper,
}
)
// ErrKeyAuthMissing is error type when PathAuth middleware is unable to extract value from lookups
var ErrKeyAuthMissing = echo.NewHTTPError(http.StatusBadRequest, "Missing key in the request")
// PathAuth returns an PathAuth middleware.
//
// For valid key it calls the next handler.
// For invalid key, it sends "401 - Unauthorized" response.
// For missing key, it sends "400 - Bad Request" response.
func PathAuth(param string, fn PathAuthValidator) echo.MiddlewareFunc {
c := DefaultKeyAuthConfig
c.Validator = fn
c.Param = param
return PathAuthWithConfig(c)
}
func PathAuthWithConfig(config PathAuthConfig) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultKeyAuthConfig.Skipper
}
if config.Validator == nil {
panic("PathAuth: requires a validator function")
}
if config.Param == "" {
panic("PathAuth: requires a param")
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
if !extract(config.Param, c.ParamNames()) {
return &echo.HTTPError{
Code: http.StatusBadRequest,
Message: http.StatusText(http.StatusBadRequest),
Internal: ErrKeyAuthMissing,
}
}
valid, err := config.Validator(c.Param(config.Param), c)
if err == nil && valid {
return next(c)
}
return &echo.HTTPError{
Code: http.StatusUnauthorized,
Message: http.StatusText(http.StatusUnauthorized),
Internal: err,
}
}
}
}
func extract(cParam string, params []string) bool {
for _, param := range params {
if cParam == param {
return true
}
}
return false
}