fix: support parameterless policy methods for guest access#727
Merged
Conversation
Laravel's Gate denies guest access when a policy method has zero parameters because policyAllowsGuests() requires a nullable \$user first param to opt in. Add checkPolicyMethod() to AuthorizableModels which uses ReflectionMethod to detect a zero-parameter policy method and calls it directly, bypassing Gate's guest-check logic. Add ParameterlessPolicyTest covering the unauthenticated-allowed, unauthenticated-denied, and authenticated-allowed scenarios.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Laravel's
Gatedenies guest access to a policy method unless that method declares a nullable$useras its first parameter.Gate::policyAllowsGuests()inspects the method signature and returnsfalsewhen the parameter is absent, so even a policy like:would return a
403for unauthenticated requests — despite explicitly returningtrue.Fix
AuthorizableModelsnow has acheckPolicyMethod()helper that usesReflectionMethodto detect when a policy method has zero parameters. In that case it calls the method directly, bypassing Gate's guest-check logic entirely. When the method does have parameters the existingGate::check()path is used unchanged.The helper is used in the four existing call sites:
authorizedToUseRepository,authorizedToStore,authorizedToStoreBulk, andauthorizedTo.Tests
tests/Feature/ParameterlessPolicyTest.phpcovers three scenarios using aParameterlessAllowPolicywhoseallowRestify()has no parameters:true(the key regression case — previously returned 403)falsetrueTest plan
./vendor/bin/phpunit tests/Feature/ParameterlessPolicyTest.php— 3 tests pass./vendor/bin/phpunit tests/Feature/AuthorizableModelsTest.php— 4 existing tests still passallowRestify(): bool { return true; }no longer returns 403 for guest requests