File size: 1,466 Bytes
ea775bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package api
import (
"net/http"
"strings"
)
// AuthMiddleware returns an http.Handler that validates the Bearer token
// in the Authorization header against the expected admin token.
// If validation fails, it returns 401 Unauthorized with a JSON error body.
func AuthMiddleware(adminToken string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Empty configured admin token means auth is intentionally disabled.
if adminToken == "" {
next.ServeHTTP(w, r)
return
}
auth := r.Header.Get("Authorization")
if auth == "" {
WriteError(w, http.StatusUnauthorized, "UNAUTHORIZED", "missing Authorization header")
return
}
const prefix = "Bearer "
if !strings.HasPrefix(auth, prefix) {
WriteError(w, http.StatusUnauthorized, "UNAUTHORIZED", "invalid Authorization header format")
return
}
token := auth[len(prefix):]
if token != adminToken {
WriteError(w, http.StatusUnauthorized, "UNAUTHORIZED", "invalid admin token")
return
}
next.ServeHTTP(w, r)
})
}
// RequestBodyLimitMiddleware enforces a max request body size for downstream handlers.
func RequestBodyLimitMiddleware(maxBytes int64, next http.Handler) http.Handler {
if maxBytes <= 0 {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r != nil && r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
next.ServeHTTP(w, r)
})
}
|