<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Utils\RequestHelper;
use App\Domain\Payload\Error;
use App\Exception\ApiException;
use App\Domain\Payload\Payload;
use OAuth2\OAuth2AuthenticateException;
use App\Exception\ApiExceptionInterface;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
class AuthExceptionSubscriber implements EventSubscriberInterface
{
/**
* @var RequestHelper
*/
private $requestHelper;
public function __construct(RequestHelper $requestHelper)
{
$this->requestHelper = $requestHelper;
}
/**
* @throws ApiExceptionInterface
*/
public function handleAuthException(AuthenticationFailureEvent $event): void
{
$oauthException = $event->getAuthenticationException()->getPrevious();
if ($oauthException instanceof OAuth2AuthenticateException && !$this->requestHelper->isV1Route()) {
$payload = new Payload();
$payload->setError(new Error(0, $oauthException->getDescription()));
throw ApiException::createUnauthorizedException($payload);
}
}
public static function getSubscribedEvents(): array
{
return [
AuthenticationEvents::AUTHENTICATION_FAILURE => ['handleAuthException', -100],
];
}
}