35 lines
1.1 KiB
Go
35 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/prabhupadasays/spsays-bff/internal/repository"
|
|
"github.com/prabhupadasays/spsays-bff/pkg/response"
|
|
)
|
|
|
|
// RequireAdmin gates a route to users whose role is "admin". It MUST run after
|
|
// RequireAuth (it reads the authenticated user id from context, then looks up
|
|
// the row to check the role). Non-admins get 403; this keeps the whole
|
|
// /api/v1/admin/* surface invisible to ordinary accounts.
|
|
func RequireAdmin(users *repository.UserRepo) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
uid := UserID(r.Context())
|
|
if uid == "" {
|
|
response.Error(w, http.StatusUnauthorized, "not authenticated")
|
|
return
|
|
}
|
|
u, err := users.FindByID(r.Context(), uid)
|
|
if err != nil {
|
|
response.Error(w, http.StatusInternalServerError, "auth check failed")
|
|
return
|
|
}
|
|
if u.Role != "admin" {
|
|
response.Error(w, http.StatusForbidden, "admin access required")
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|