x/net/http/auth.go
Colin Henry fe49018479
Some checks failed
Go / build (1.19) (push) Failing after 22s
added new check capability and added assets to a few other packages
2024-09-28 15:19:00 -07:00

33 lines
888 B
Go

package http
import (
"crypto/sha1"
"encoding/base64"
"fmt"
"net/http"
"strings"
"git.sdf.org/jchenry/x"
)
func BasicAuth(h http.Handler, htpasswd map[string]string, realm string) http.HandlerFunc {
x.Assert(len(htpasswd) > 0, "http.BasicAuth: htpassword cannot be empty")
x.Assert(len(realm) > 0, "http.BasicAuth: realm cannot be empty")
rlm := fmt.Sprintf(`Basic realm="%s"`, realm)
sha1 := func(password string) string {
s := sha1.New()
_, _ = s.Write([]byte(password))
passwordSum := []byte(s.Sum(nil))
return base64.StdEncoding.EncodeToString(passwordSum)
}
return func(w http.ResponseWriter, r *http.Request) {
user, pass, _ := r.BasicAuth()
if pw, ok := htpasswd[user]; !ok || !strings.EqualFold(pass, sha1(pw)) {
w.Header().Set("WWW-Authenticate", rlm)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
}
}