makeing BasicAuth a little more generic and usable

This commit is contained in:
Colin Henry 2020-08-18 19:18:03 -07:00
parent 85df14e0c6
commit 15ef3556ba

View File

@ -1,19 +1,28 @@
package http package http
import ( import (
"crypto/sha1"
"encoding/base64"
"fmt"
"net/http" "net/http"
"os" "strings"
) )
func BasicAuth(h http.Handler) http.HandlerFunc { 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)
}
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
user, pass, _ := r.BasicAuth() user, pass, _ := r.BasicAuth()
if !(user == os.Getenv("WIKI_USERNAME") && pass == os.Getenv("WIKI_PASSWORD")) { if pw, ok := htpasswd[user]; !ok || !strings.EqualFold(pass, sha1(pw)) {
w.Header().Set("WWW-Authenticate", `Basic realm="wiki"`) w.Header().Set("WWW-Authenticate", rlm)
http.Error(w, "Unauthorized.", 401) http.Error(w, "Unauthorized.", 401)
return return
} }
h.ServeHTTP(w, r) h.ServeHTTP(w, r)
} }
} }