forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
64 lines (55 loc) · 1.57 KB
/
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
package middleware
import (
"encoding/base64"
"github.com/labstack/echo"
)
type (
// BasicAuthConfig defines config for HTTP basic auth middleware.
BasicAuthConfig struct {
AuthFunc BasicAuthFunc
}
// BasicAuthFunc defines a function to validate basic auth credentials.
BasicAuthFunc func(string, string) bool
)
const (
basic = "Basic"
)
var (
// DefaultBasicAuthConfig is the default basic auth middleware config.
DefaultBasicAuthConfig = BasicAuthConfig{}
)
// BasicAuth returns an HTTP basic auth middleware.
//
// For valid credentials it calls the next handler.
// For invalid credentials, it sends "401 - Unauthorized" response.
func BasicAuth(f BasicAuthFunc) echo.MiddlewareFunc {
c := DefaultBasicAuthConfig
c.AuthFunc = f
return BasicAuthFromConfig(c)
}
// BasicAuthFromConfig returns an HTTP basic auth middleware from config.
// See `BasicAuth()`.
func BasicAuthFromConfig(config BasicAuthConfig) echo.MiddlewareFunc {
return func(next echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error {
auth := c.Request().Header().Get(echo.Authorization)
l := len(basic)
if len(auth) > l+1 && auth[:l] == basic {
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
if err == nil {
cred := string(b)
for i := 0; i < len(cred); i++ {
if cred[i] == ':' {
// Verify credentials
if config.AuthFunc(cred[:i], cred[i+1:]) {
return next.Handle(c)
}
}
}
}
}
c.Response().Header().Set(echo.WWWAuthenticate, basic+" realm=Restricted")
return echo.ErrUnauthorized
})
}
}