From 74097bd47c050cd3ddd1c3ccf7eef3a20bc463a3 Mon Sep 17 00:00:00 2001 From: Thomas Kuschan Date: Wed, 14 Jun 2023 11:52:22 +0200 Subject: [PATCH] Simplify ApiAuthException control flow Remove unnecessary UnauthorizedException and make ApiAuthException compatible with HttpExceptionInterface. Move the creation of a rsponse for the exception from ApiAuthenticate middleware into the application exception handler. --- app/Exceptions/ApiAuthException.php | 21 ++++++++++++++++++++- app/Exceptions/UnauthorizedException.php | 16 ---------------- app/Http/Middleware/ApiAuthenticate.php | 24 ++++-------------------- 3 files changed, 24 insertions(+), 37 deletions(-) delete mode 100644 app/Exceptions/UnauthorizedException.php diff --git a/app/Exceptions/ApiAuthException.php b/app/Exceptions/ApiAuthException.php index 360370de4..070f7a8df 100644 --- a/app/Exceptions/ApiAuthException.php +++ b/app/Exceptions/ApiAuthException.php @@ -2,6 +2,25 @@ namespace BookStack\Exceptions; -class ApiAuthException extends UnauthorizedException +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; + +class ApiAuthException extends \Exception implements HttpExceptionInterface { + protected int $status; + + public function __construct(string $message, int $statusCode = 401) + { + $this->status = $statusCode; + parent::__construct($message, $statusCode); + } + + public function getStatusCode(): int + { + return $this->status; + } + + public function getHeaders(): array + { + return []; + } } diff --git a/app/Exceptions/UnauthorizedException.php b/app/Exceptions/UnauthorizedException.php deleted file mode 100644 index 5c73ca02c..000000000 --- a/app/Exceptions/UnauthorizedException.php +++ /dev/null @@ -1,16 +0,0 @@ -ensureAuthorizedBySessionOrToken(); - } catch (UnauthorizedException $exception) { - return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode()); - } + $this->ensureAuthorizedBySessionOrToken(); return $next($request); } @@ -28,7 +25,7 @@ class ApiAuthenticate * Ensure the current user can access authenticated API routes, either via existing session * authentication or via API Token authentication. * - * @throws UnauthorizedException + * @throws ApiAuthException */ protected function ensureAuthorizedBySessionOrToken(): void { @@ -58,17 +55,4 @@ class ApiAuthenticate return $hasApiPermission && hasAppAccess(); } - - /** - * Provide a standard API unauthorised response. - */ - protected function unauthorisedResponse(string $message, int $code) - { - return response()->json([ - 'error' => [ - 'code' => $code, - 'message' => $message, - ], - ], $code); - } }