Added BasicAuth to admin handlers. (SommerEngineering/KPIManager#8)

This commit is contained in:
DiddiZ committed 2017-02-02 22:15:48 +01:00
1 parent 4a01aaf9bd
commit 46edc84421
4 files changed
+34 -2

No files matched your search

+2 -1
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"github.com/SommerEngineering/Ocean/ConfigurationDB"
"github.com/SommerEngineering/Ocean/Log"
LM "github.com/SommerEngineering/Ocean/Log/Meta"
)
@@ -33,5 +34,5 @@ func AddAdminHandler(pattern string, handler func(http.ResponseWriter, *http.Req
}()
// Add the handler:
muxAdmin.HandleFunc(pattern, handler)
muxAdmin.HandleFunc(pattern, BasicAuth(handler, `admin`, ConfigurationDB.Read(`AdminWebServerEnabled`), `Please enter your username and password for this site`))
}
+30
View File
@@ -0,0 +1,30 @@
package Handlers
import (
"crypto/subtle"
"net/http"
)
// BasicAuth wraps a handler requiring HTTP basic auth for it using the given
// username and password and the specified realm, which shouldn't contain quotes.
//
// Most web browser display a dialog with something like:
//
// The website says: "<realm>"
//
// Which is really stupid so you may want to set the realm to a message rather than
// an actual realm.
//
// Taken from on http://stackoverflow.com/questions/21936332/idiomatic-way-of-requiring-http-basic-auth-in-go/39591234#39591234
func BasicAuth(handler http.HandlerFunc, username, password, realm string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(401)
w.Write([]byte(http.StatusText(401)))
return
}
handler(w, r)
}
}