generated from CubeCraft-Creations/Tracehound
CUB-184: API key auth middleware
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
// Package auth provides API key authentication middleware.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Middleware returns a Chi middleware that validates the X-API-Key header.
|
||||
func Middleware(apiKey string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("X-API-Key")
|
||||
if apiKey == "" {
|
||||
// No API key configured — allow all requests (kiosk mode)
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if header == "" || header != apiKey {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"error":"unauthorized"}`))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ExtractKey reads and returns the API key from the request, or empty string.
|
||||
func ExtractKey(r *http.Request) string {
|
||||
return r.Header.Get("X-API-Key")
|
||||
}
|
||||
Reference in New Issue
Block a user