Fix support for authorization using sanctum tokens

This commit is contained in:
Dane Everitt 2021-07-28 21:05:23 -07:00
parent 1a3451fb0d
commit 374910d73a
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
2 changed files with 24 additions and 1 deletions

View file

@ -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()),
],
]);

View file

@ -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.
*