Files
minstrel/internal/auth/admin.go
T
bvandeusenandClaude Opus 5.5 da21becead Revert the deliberate break (#8299)
Run 11302 failed all ten named tests, and with them apierror's
TestWrite_SendsTheEnvelopeAndHidesAPlainErrorsText and api's
TestFlag_BadReason, which pin the same rules from the handler side.

This reverts commit 21adbc2283.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:30:55 -05:00

38 lines
1.1 KiB
Go

package auth
import (
"net/http"
"github.com/Fabled-Sword/minstrel/internal/apierror"
)
// RequireAdmin is a middleware that MUST run after RequireUser. It reads the
// authenticated user from request context and rejects non-admin callers with
// 403. If no user is in context (RequireUser was bypassed), it returns 500 —
// that is a programmer error in the routing setup, not a client error.
//
// Mount this on /api/admin/* after auth.RequireUser:
//
// r.Route("/api/admin", func(admin chi.Router) {
// admin.Use(auth.RequireUser(pool))
// admin.Use(auth.RequireAdmin())
// ...
// })
func RequireAdmin() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
// Programmer error: RequireUser was not mounted before RequireAdmin.
apierror.Write(w, apierror.InternalMsg("admin check mounted without a user", nil))
return
}
if !user.IsAdmin {
apierror.Write(w, apierror.Forbidden("not_authorized", "admin access required"))
return
}
next.ServeHTTP(w, r)
})
}
}