From 374910d73a8a68d2cccad767da399334b32ea80f Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Wed, 28 Jul 2021 21:05:23 -0700 Subject: [PATCH] Fix support for authorization using sanctum tokens --- app/Exceptions/Handler.php | 14 +++++++++++++- app/Models/PersonalAccessToken.php | 11 +++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index a94ad8aad..38ac2eb27 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -8,6 +8,7 @@ use PDOException; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Swift_TransportException; +use Illuminate\Http\Response; use Illuminate\Http\JsonResponse; use Illuminate\Support\Collection; use Illuminate\Container\Container; @@ -59,6 +60,16 @@ class Handler extends ExceptionHandler 'password_confirmation', ]; + /** + * Maps specific internal exceptions to a valid HTTP status code. + * + * @var array + */ + protected static $statusCodeMap = [ + AuthenticationException::class => Response::HTTP_UNAUTHORIZED, + ValidationException::class => Response::HTTP_UNPROCESSABLE_ENTITY, + ]; + /** * Registers the exception handling callbacks for the application. This * will capture specific exception types that we do not want to include @@ -191,7 +202,7 @@ class Handler extends ExceptionHandler 'code' => class_basename($exception), 'status' => method_exists($exception, 'getStatusCode') ? strval($exception->getStatusCode()) - : ($exception instanceof ValidationException ? '422' : '500'), + : strval(self::$statusCodeMap[get_class($exception)] ?? 500), 'detail' => $exception instanceof HttpExceptionInterface ? $exception->getMessage() : 'An unexpected error was encountered while processing this request, please try again.', @@ -212,6 +223,7 @@ class Handler extends ExceptionHandler 'file' => str_replace(Application::getInstance()->basePath(), '', $exception->getFile()), ], 'meta' => [ + 'class' => get_class($exception), 'trace' => explode("\n", $exception->getTraceAsString()), ], ]); diff --git a/app/Models/PersonalAccessToken.php b/app/Models/PersonalAccessToken.php index 0398a0b20..1ab887964 100644 --- a/app/Models/PersonalAccessToken.php +++ b/app/Models/PersonalAccessToken.php @@ -36,6 +36,17 @@ class PersonalAccessToken extends Model implements HasAbilities return $this->belongsTo(User::class); } + /** + * Required for support with Laravel Sanctum. + * + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + * @see \Laravel\Sanctum\Guard::supportsTokens() + */ + public function tokenable() + { + return $this->user(); + } + /** * Determine if the token has a given ability. *