From 997788acd9de3f73fc61a217e7494a7a4ed12e6f Mon Sep 17 00:00:00 2001 From: Gregory Haddow Date: Mon, 2 Dec 2024 11:15:39 +0000 Subject: [PATCH] fix: authorizer response with status should be honoured when unauthenticated --- src/Http/Requests/FormRequest.php | 4 +++- tests/dummy/app/Policies/UserPolicy.php | 6 +++--- tests/dummy/tests/Api/V1/Users/DeleteTest.php | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/Http/Requests/FormRequest.php b/src/Http/Requests/FormRequest.php index a4974ca..928b489 100644 --- a/src/Http/Requests/FormRequest.php +++ b/src/Http/Requests/FormRequest.php @@ -254,7 +254,9 @@ protected function passesAuthorization() } } catch (AuthorizationException $ex) { - $this->failIfUnauthenticated(); + if (!$ex->hasStatus()) { + $this->failIfUnauthenticated(); + } throw $ex; } return true; diff --git a/tests/dummy/app/Policies/UserPolicy.php b/tests/dummy/app/Policies/UserPolicy.php index 6fc202c..c2b6224 100644 --- a/tests/dummy/app/Policies/UserPolicy.php +++ b/tests/dummy/app/Policies/UserPolicy.php @@ -55,13 +55,13 @@ public function updatePhone(User $user, User $other): bool /** * Determine if the user can delete the other user. * - * @param User $user + * @param ?User $user * @param User $other * @return bool|Response */ - public function delete(User $user, User $other) + public function delete(?User $user, User $other) { - return $user->is($other) ? true : Response::denyAsNotFound('not found message'); + return $user?->is($other) ? true : Response::denyAsNotFound('not found message'); } } diff --git a/tests/dummy/tests/Api/V1/Users/DeleteTest.php b/tests/dummy/tests/Api/V1/Users/DeleteTest.php index 4980767..6679084 100644 --- a/tests/dummy/tests/Api/V1/Users/DeleteTest.php +++ b/tests/dummy/tests/Api/V1/Users/DeleteTest.php @@ -35,4 +35,22 @@ public function test(): void 'title' => 'Not Found', ]); } + + public function testUnauthenticated(): void + { + $user = User::factory()->createOne(); + + $expected = $this->serializer + ->user($user); + $response = $this + ->jsonApi('users') + ->delete(url('/api/v1/users', $expected['id'])); + + $response->assertNotFound() + ->assertHasError(404, [ + 'detail' => 'not found message', + 'status' => '404', + 'title' => 'Not Found', + ]); + } }