x/net/http/auth.go

29 lines
701 B
Go
Raw Normal View History

2020-06-12 00:26:57 -04:00
package http
import (
"crypto/sha1"
"encoding/base64"
"fmt"
2020-06-12 00:26:57 -04:00
"net/http"
"strings"
2020-06-12 00:26:57 -04:00
)
func BasicAuth(h http.Handler, htpasswd map[string]string, realm string) http.HandlerFunc {
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)
}
2020-06-12 00:26:57 -04:00
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)
2020-06-12 00:26:57 -04:00
http.Error(w, "Unauthorized.", 401)
return
}
2020-07-27 20:20:10 -04:00
h.ServeHTTP(w, r)
2020-06-12 00:26:57 -04:00
}
}