forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
51 lines (44 loc) · 1.23 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
package middleware
import (
"encoding/base64"
"net/http"
echo "gopkg.in/labstack/echo.v1"
)
type (
// BasicValidateFunc is the expected format a BasicAuth fn argument is
// expected to implement.
BasicValidateFunc func(string, string) bool
)
const (
// Basic is the authentication scheme implemented by the middleware.
Basic = "Basic"
)
// BasicAuth returns a HTTP basic authentication middleware.
// For valid credentials, it calls the next handler.
// For invalid credentials, it returns a "401 Unauthorized" HTTP error.
func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Skip WebSocket
if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
return nil
}
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 fn(cred[:i], cred[i+1:]) {
return nil
}
}
}
}
}
c.Response().Header().Set(echo.WWWAuthenticate, Basic+" realm=Restricted")
return echo.NewHTTPError(http.StatusUnauthorized)
}
}