Files
2026-06-10 16:32:46 +02:00

50 lines
1.1 KiB
Go

package auth
import (
"encoding/json"
"net/http"
"strings"
)
type Middleware struct {
validator *Validator
}
func NewMiddleware(validator *Validator) Middleware {
return Middleware{validator: validator}
}
func (m Middleware) RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := bearerToken(r.Header.Get("Authorization"))
if !ok {
writeUnauthorized(w)
return
}
principal, err := m.validator.Validate(r.Context(), token)
if err != nil {
writeUnauthorized(w)
return
}
next.ServeHTTP(w, r.WithContext(ContextWithPrincipal(r.Context(), principal)))
})
}
func bearerToken(header string) (string, bool) {
const prefix = "Bearer "
if !strings.HasPrefix(header, prefix) {
return "", false
}
token := strings.TrimSpace(strings.TrimPrefix(header, prefix))
return token, token != ""
}
func writeUnauthorized(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
}