Rework basic auth
This commit is contained in:
@@ -1,17 +1,44 @@
|
||||
package handlers
|
||||
|
||||
import "net/http"
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// basicAuth is a middleware that performs basic authentication.
|
||||
func (hs *Handlers) basicAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username != hs.cfg.GetUsername() || password != hs.cfg.GetPassword() {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="restricted"`)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(http.StatusText(http.StatusUnauthorized)))
|
||||
return
|
||||
if r.Method != "OPTIONS" && needsAuth(r.URL.Path) {
|
||||
if !hs.authenticate(r) {
|
||||
hs.unauthorized(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// needsAuth checks if the given path requires authentication.
|
||||
func needsAuth(path string) bool {
|
||||
authenticatedPaths := []string{"/dav/", "/infuse/"}
|
||||
for _, p := range authenticatedPaths {
|
||||
if strings.HasPrefix(path, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// authenticate performs the basic authentication check.
|
||||
func (hs *Handlers) authenticate(r *http.Request) bool {
|
||||
username, password, ok := r.BasicAuth()
|
||||
return ok && username == hs.cfg.GetUsername() && password == hs.cfg.GetPassword()
|
||||
}
|
||||
|
||||
// unauthorized sends an unauthorized response.
|
||||
func (hs *Handlers) unauthorized(w http.ResponseWriter) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="restricted"`)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(http.StatusText(http.StatusUnauthorized)))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user