package middleware import ( "RenewCMS/api/pkg/access" "RenewCMS/internal/domain/role" "RenewCMS/internal/domain/user" "RenewCMS/internal/infrastructure/useCases" "net/http" ) type grantCheck func(account user.User, key string) (role.GrantSet, error) func RequirePermission(getUser *useCases.GetUserUseCase, check *useCases.CheckPermissionUseCase, key string) func(http.Handler) http.Handler { return enforce(getUser, check.Require, key) } func RequireFullScope(getUser *useCases.GetUserUseCase, check *useCases.CheckPermissionUseCase, key string) func(http.Handler) http.Handler { return enforce(getUser, check.RequireAll, key) } func enforce(getUser *useCases.GetUserUseCase, verify grantCheck, key string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { currentUser, ok := resolveCurrentUser(getUser, w, r) if !ok { return } grants, err := verify(currentUser, key) if err != nil { if !access.WriteIfMissingPermission(w, err) { http.Error(w, "Internal server error", http.StatusInternalServerError) } return } next.ServeHTTP(w, r.WithContext(access.NewContext(r.Context(), grants))) }) } }