-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
44 lines (36 loc) · 1.03 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
package middleware
import (
"crypto/subtle"
"net/http"
"github.com/komuw/ong/internal/key"
)
// BasicAuth is a middleware that protects wrappedHandler using basic authentication.
func BasicAuth(wrappedHandler http.Handler, user, passwd, hint string) http.HandlerFunc {
if err := key.IsSecure(passwd); err != nil {
panic(err)
}
// See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
realm := `enter username and password: ` + hint
e := func(w http.ResponseWriter) {
errMsg := `Basic realm=` + realm
w.Header().Set("WWW-Authenticate", errMsg)
w.Header().Set(ongMiddlewareErrorHeader, errMsg)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
return func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
if u == "" || p == "" || !ok {
e(w)
return
}
if subtle.ConstantTimeCompare([]byte(u), []byte(user)) != 1 {
e(w)
return
}
if subtle.ConstantTimeCompare([]byte(p), []byte(passwd)) != 1 {
e(w)
return
}
wrappedHandler.ServeHTTP(w, r)
}
}