-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
35 lines (30 loc) · 1.02 KB
/
auth.go
File metadata and controls
35 lines (30 loc) · 1.02 KB
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
package peerdb
import (
"crypto/sha256"
"crypto/subtle"
"net/http"
"gitlab.com/tozd/waf"
)
// hasherSHA256 computes the SHA256 hash of a string for constant-time credential comparison.
func hasherSHA256(s string) []byte {
val := sha256.Sum256([]byte(s))
return val[:]
}
func basicAuthHandler(username string, password string) func(http.Handler) http.Handler {
usernameHash := hasherSHA256(username)
passwordHash := hasherSHA256(password)
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
site := waf.MustGetSite[*Site](req.Context())
user, pass, ok := req.BasicAuth()
userCompare := subtle.ConstantTimeCompare(hasherSHA256(user), usernameHash)
passwordCompare := subtle.ConstantTimeCompare(hasherSHA256(pass), passwordHash)
if !ok || userCompare+passwordCompare != 2 {
w.Header().Set("WWW-Authenticate", `Basic realm="`+site.Title+`"`)
waf.Error(w, req, http.StatusUnauthorized)
return
}
handler.ServeHTTP(w, req)
})
}
}