From e5286c3c09e5a5e6bfce5c5f063bff04b76d383c Mon Sep 17 00:00:00 2001 From: CWAscend <134165900+CWAscend@users.noreply.github.com> Date: Mon, 10 Feb 2025 00:41:37 +0000 Subject: [PATCH] Injects route parameters into action authorize --- src/Concerns/ValidateActions.php | 6 +++++- .../AsControllerWithAuthorizeAndRulesTest.php | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Concerns/ValidateActions.php b/src/Concerns/ValidateActions.php index 3b788fd..c07e8e0 100644 --- a/src/Concerns/ValidateActions.php +++ b/src/Concerns/ValidateActions.php @@ -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(); diff --git a/tests/AsControllerWithAuthorizeAndRulesTest.php b/tests/AsControllerWithAuthorizeAndRulesTest.php index 1df3aca..73b7ae1 100644 --- a/tests/AsControllerWithAuthorizeAndRulesTest.php +++ b/tests/AsControllerWithAuthorizeAndRulesTest.php @@ -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 () { @@ -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(); +});