src/EventSubscriber/AuthExceptionSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Utils\RequestHelper;
  5. use App\Domain\Payload\Error;
  6. use App\Exception\ApiException;
  7. use App\Domain\Payload\Payload;
  8. use OAuth2\OAuth2AuthenticateException;
  9. use App\Exception\ApiExceptionInterface;
  10. use Symfony\Component\Security\Core\AuthenticationEvents;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
  13. class AuthExceptionSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var RequestHelper
  17.      */
  18.     private $requestHelper;
  19.     public function __construct(RequestHelper $requestHelper)
  20.     {
  21.         $this->requestHelper $requestHelper;
  22.     }
  23.     /**
  24.      * @throws ApiExceptionInterface
  25.      */
  26.     public function handleAuthException(AuthenticationFailureEvent $event): void
  27.     {
  28.         $oauthException $event->getAuthenticationException()->getPrevious();
  29.         if ($oauthException instanceof OAuth2AuthenticateException && !$this->requestHelper->isV1Route()) {
  30.             $payload = new Payload();
  31.             $payload->setError(new Error(0$oauthException->getDescription()));
  32.             throw ApiException::createUnauthorizedException($payload);
  33.         }
  34.     }
  35.     public static function getSubscribedEvents(): array
  36.     {
  37.         return [
  38.             AuthenticationEvents::AUTHENTICATION_FAILURE => ['handleAuthException', -100],
  39.         ];
  40.     }
  41. }