From 15ef3556ba8f78edcf8a67e0e50d2d3fba6f42b0 Mon Sep 17 00:00:00 2001 From: Colin Henry Date: Tue, 18 Aug 2020 19:18:03 -0700 Subject: [PATCH] makeing BasicAuth a little more generic and usable --- net/http/auth.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/net/http/auth.go b/net/http/auth.go index ac5c9ce..f84a366 100644 --- a/net/http/auth.go +++ b/net/http/auth.go @@ -1,19 +1,28 @@ package http import ( + "crypto/sha1" + "encoding/base64" + "fmt" "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) { user, pass, _ := r.BasicAuth() - if !(user == os.Getenv("WIKI_USERNAME") && pass == os.Getenv("WIKI_PASSWORD")) { - w.Header().Set("WWW-Authenticate", `Basic realm="wiki"`) + if pw, ok := htpasswd[user]; !ok || !strings.EqualFold(pass, sha1(pw)) { + w.Header().Set("WWW-Authenticate", rlm) http.Error(w, "Unauthorized.", 401) return } - h.ServeHTTP(w, r) } }