Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injects route parameters into action authorize #308

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Concerns/ValidateActions.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,12 @@ protected function getErrorBag(Validator $validator): string
protected function inspectAuthorization(): Response
{
try {
$routeParameters = method_exists($this, 'route') ? $this->route()->parameters() : null;

$response = $this->hasMethod('authorize')
? $this->resolveAndCallMethod('authorize')
? ($routeParameters
? $this->resolveAndCallMethod('authorize', $routeParameters)
: $this->resolveAndCallMethod('authorize'))
: true;
} catch (AuthorizationException $e) {
return $e->toResponse();
Expand Down
21 changes: 21 additions & 0 deletions tests/AsControllerWithAuthorizeAndRulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,25 @@ public function handle(ActionRequest $request)
}
}

class AsControllerWithAuthorizeBindingsTest
{
use AsController;

public function authorize(string $someRouteParameter): bool
{
return $someRouteParameter !== 'unauthorized';
}

public function handle(ActionRequest $request, string $someRouteParameter)
{
return [$someRouteParameter];
}
}

beforeEach(function () {
// Given the action is registered as a controller.
Route::post('/calculator', AsControllerWithAuthorizeAndRulesTest::class);
Route::get('/authorize-bindings/{someRouteParameter}', AsControllerWithAuthorizeBindingsTest::class);
});

it('passes authorization and validation', function () {
Expand Down Expand Up @@ -86,3 +102,8 @@ public function handle(ActionRequest $request)
$this->post('/calculator', ['operation' => 'invalid'])
->assertSessionHasErrors(['operation', 'right', 'left']);
});

it('resolves route parameters as authorization arguments', function () {
$this->get('/authorize-bindings/authorized')->assertOk()->assertExactJson(['authorized']);
$this->get('/authorize-bindings/unauthorized')->assertForbidden();
});