34 lines
779 B
Go
34 lines
779 B
Go
package authorization
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"proxui/backend/internal/membership"
|
|
"proxui/backend/internal/rbac"
|
|
)
|
|
|
|
type Middleware struct{}
|
|
|
|
func NewMiddleware() Middleware {
|
|
return Middleware{}
|
|
}
|
|
|
|
func (m Middleware) Require(action rbac.Action, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
membership, ok := membership.FromRequest(r)
|
|
if !ok || !rbac.Can(membership.Role, action) {
|
|
writeError(w, http.StatusForbidden, "forbidden")
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, message string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
|
|
}
|