nomadcode/internal/http/middleware.go

66 lines
1.6 KiB
Go

package http
import (
"crypto/subtle"
"log/slog"
stdhttp "net/http"
"time"
)
type statusRecorder struct {
stdhttp.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func loggingMiddleware(logger *slog.Logger) func(stdhttp.Handler) stdhttp.Handler {
return func(next stdhttp.Handler) stdhttp.Handler {
return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
start := time.Now()
recorder := &statusRecorder{ResponseWriter: w, status: stdhttp.StatusOK}
next.ServeHTTP(recorder, r)
if logger != nil {
logger.Info(
"http request",
"method", r.Method,
"path", r.URL.Path,
"status", recorder.status,
"duration", time.Since(start).String(),
)
}
})
}
}
func basicAuthMiddleware(auth AuthConfig) func(stdhttp.Handler) stdhttp.Handler {
if auth.Password == "" {
return func(next stdhttp.Handler) stdhttp.Handler {
return next
}
}
if auth.Username == "" {
auth.Username = "nomadcode"
}
return func(next stdhttp.Handler) stdhttp.Handler {
return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
username, password, ok := r.BasicAuth()
if !ok || !secureCompare(username, auth.Username) || !secureCompare(password, auth.Password) {
w.Header().Set("WWW-Authenticate", `Basic realm="nomadcode-core", charset="UTF-8"`)
writeError(w, stdhttp.StatusUnauthorized, "authentication required")
return
}
next.ServeHTTP(w, r)
})
}
}
func secureCompare(got, want string) bool {
return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
}