Files
httpauth/authz.go

33 lines
1.0 KiB
Go
Raw Permalink Normal View History

package httpauth
import (
"net/http"
"code.nochebuena.dev/go/rbac"
)
// AuthzMiddleware reads the rbac.Identity from context (set by EnrichmentMiddleware)
// and gates the request against the required permission on resource.
// Uses rbac.PermissionProvider directly — no local redefinition of the interface.
// Returns 401 if no identity is in context.
// Returns 403 if the identity lacks the required permission or if the provider errors.
func AuthzMiddleware(provider rbac.PermissionProvider, resource string, required rbac.Permission) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
identity, ok := rbac.FromContext(r.Context())
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
mask, err := provider.ResolveMask(r.Context(), identity.UID, resource)
if err != nil || !mask.Has(required) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}