forked from gomods/athens
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basicauth.go
42 lines (34 loc) · 1.03 KB
/
basicauth.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
package actions
import (
"crypto/subtle"
"net/http"
"regexp"
"github.com/gorilla/mux"
)
// basicAuthExcludedPaths is a regular expression that matches paths that should not be protected by HTTP basic authentication.
var basicAuthExcludedPaths = regexp.MustCompile("^/(health|ready)z$")
func basicAuth(user, pass string) mux.MiddlewareFunc {
return func(h http.Handler) http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
if !basicAuthExcludedPaths.MatchString(r.URL.Path) && !checkAuth(r, user, pass) {
w.Header().Set("WWW-Authenticate", `Basic realm="basic auth required"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(f)
}
}
func checkAuth(r *http.Request, user, pass string) bool {
givenUser, givenPass, ok := r.BasicAuth()
if !ok {
return false
}
isUser := subtle.ConstantTimeCompare([]byte(user), []byte(givenUser))
if isUser != 1 {
return false
}
isPass := subtle.ConstantTimeCompare([]byte(pass), []byte(givenPass))
return isPass == 1
}