-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
basic_auth.go
47 lines (40 loc) · 1.4 KB
/
basic_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
package rest
import (
"context"
"crypto/subtle"
"net/http"
)
const baContextKey = "authorizedWithBasicAuth"
// BasicAuth middleware requires basic auth and matches user & passwd with client-provided checker
func BasicAuth(checker func(user, passwd string) bool) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
if !checker(u, p) {
w.WriteHeader(http.StatusForbidden)
return
}
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), contextKey(baContextKey), true)))
}
return http.HandlerFunc(fn)
}
}
// BasicAuthWithUserPasswd middleware requires basic auth and matches user & passwd with client-provided values
func BasicAuthWithUserPasswd(user, passwd string) func(http.Handler) http.Handler {
checkFn := func(reqUser, reqPasswd string) bool {
matchUser := subtle.ConstantTimeCompare([]byte(user), []byte(reqUser))
matchPass := subtle.ConstantTimeCompare([]byte(passwd), []byte(reqPasswd))
return matchUser == 1 && matchPass == 1
}
return BasicAuth(checkFn)
}
// IsAuthorized returns true is user authorized.
// it can be used in handlers to check if BasicAuth middleware was applied
func IsAuthorized(ctx context.Context) bool {
v := ctx.Value(contextKey(baContextKey))
return v != nil && v.(bool)
}