2021-03-23 00:46:33 +00:00
|
|
|
package fuphttp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/subtle"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
)
|
|
|
|
|
2021-03-23 00:58:06 +00:00
|
|
|
func tokenFromRequest(r *http.Request) (token string, ok bool) {
|
|
|
|
// Check for a Fup-Token header.
|
|
|
|
v := r.Header.Get("Fup-Token")
|
|
|
|
if v != "" {
|
|
|
|
return v, true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for basic auth.
|
|
|
|
_, v, ok = r.BasicAuth()
|
|
|
|
return v, ok
|
|
|
|
}
|
|
|
|
|
2021-03-23 00:46:33 +00:00
|
|
|
func TokenAuthMiddleware(token, realm string) mux.MiddlewareFunc {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
if token == "" {
|
|
|
|
return next
|
|
|
|
}
|
|
|
|
tokenBytes := []byte(token)
|
|
|
|
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
if !IsMutate(ctx) {
|
|
|
|
// Allow all access to public pages.
|
|
|
|
next.ServeHTTP(rw, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
requestAuth := func(s string) {
|
|
|
|
rw.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q, charset=\"UTF-8\"", realm))
|
|
|
|
http.Error(rw, s, http.StatusUnauthorized)
|
|
|
|
}
|
|
|
|
|
2021-03-23 00:58:06 +00:00
|
|
|
pw, ok := tokenFromRequest(r)
|
2021-03-23 00:46:33 +00:00
|
|
|
switch {
|
|
|
|
case !ok:
|
|
|
|
requestAuth("unparsable or no credentials")
|
|
|
|
return
|
|
|
|
case subtle.ConstantTimeCompare([]byte(pw), tokenBytes) != 1:
|
|
|
|
requestAuth("bad credentials")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Auth check passed, let's go.
|
|
|
|
next.ServeHTTP(rw, r)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|