feat: add tenant authorization middleware
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
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})
|
||||
}
|
||||
Reference in New Issue
Block a user