diff --git a/CHANGELOG.md b/CHANGELOG.md index 5083798..8c152ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Support extending schema using partial GraphQL schema files. +### Added +- Handle `Illuminate\Auth\Access\AuthorizationException` exceptions. + ## [10.0.0] - 2023-03-02 ### Changed diff --git a/src/Concerns/HandlesGraphqlRequests.php b/src/Concerns/HandlesGraphqlRequests.php index c1e015f..84c8e38 100644 --- a/src/Concerns/HandlesGraphqlRequests.php +++ b/src/Concerns/HandlesGraphqlRequests.php @@ -21,6 +21,7 @@ use GraphQL\Type\Schema; use GraphQL\Utils\BuildSchema; use GraphQL\Utils\SchemaExtender; +use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Database\Eloquent\MissingAttributeException; use Illuminate\Database\Eloquent\ModelNotFoundException; @@ -109,6 +110,16 @@ public function errorFormatter(GraphqlError $graphqlError) $throwable instanceof Exception ? $throwable : $graphqlError ); + if ($throwable instanceof AuthorizationException) { + return array_merge($formattedError, [ + 'message' => $throwable->getMessage(), + 'extensions' => [ + 'category' => 'client', + 'code' => $throwable->status() ?: 403, + ], + ]); + } + if ( $throwable instanceof HttpException && $throwable->getStatusCode() >= 400 && diff --git a/tests/HandlesGraphqlRequestsTest.php b/tests/HandlesGraphqlRequestsTest.php index 0428777..f5c1dbe 100644 --- a/tests/HandlesGraphqlRequestsTest.php +++ b/tests/HandlesGraphqlRequestsTest.php @@ -289,6 +289,18 @@ public function test_error_with_trace() $this->assertSame('internal', Arr::get($data, 'errors.0.extensions.category')); } + public function test_authorization_error_is_formatted() + { + $controller = $this->app->make(GraphqlController::class); + $data = $controller(Request::create('/', 'POST', [ + 'query' => '{ throwAuthorizationException }', + ])); + + $this->assertSame('This action is unauthorized.', data_get($data, 'errors.0.message')); + $this->assertSame('client', data_get($data, 'errors.0.extensions.category')); + $this->assertSame(403, data_get($data, 'errors.0.extensions.code')); + } + public function test_http_client_error_is_formatted() { $controller = $this->app->make(GraphqlController::class); diff --git a/tests/stubs/Queries/ThrowAuthorizationException.php b/tests/stubs/Queries/ThrowAuthorizationException.php new file mode 100644 index 0000000..19b75b4 --- /dev/null +++ b/tests/stubs/Queries/ThrowAuthorizationException.php @@ -0,0 +1,13 @@ +