src/Listener/JWT/AuthenticationFailureListener.php line 20

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Listener\JWT;
  4. use App\Exception\Auth\AuthenticationFailedException;
  5. use App\Exception\User\UserAccountLoginNotAllowedException;
  6. use App\Exception\User\UserAccountNotFoundException;
  7. use App\Exception\User\UserPasswordInvalid;
  8. use App\Tool\Encryption\JWTDecoder;
  9. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
  10. use Lexik\Bundle\JWTAuthenticationBundle\Exception\MissingTokenException;
  11. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  12. class AuthenticationFailureListener
  13. {
  14.     private array $customExceptions = [UserAccountLoginNotAllowedException::class, UserAccountNotFoundException::class];
  15.     public function onAuthenticationFailure(AuthenticationFailureEvent $event): void
  16.     {
  17.         $additionalInfo = [];
  18.         $exception $event->getException();
  19.         if (!$exception instanceof MissingTokenException) {
  20.             $jwtToken $event->getRequest()->headers->get('authorization');
  21.             if (!empty($jwtToken)){
  22.                 $decodedJwtToken JWTDecoder::decode($jwtToken);
  23.                 if(is_array($decodedJwtToken)) {
  24.                     $additionalInfo = [
  25.                         'userId' => array_key_exists('id'$decodedJwtToken) ? $decodedJwtToken['id'] : '',
  26.                         'username' => array_key_exists('username'$decodedJwtToken) ? $decodedJwtToken['username'] : ''
  27.                     ];
  28.                 }
  29.             }
  30.         }
  31.         $nestedException $exception $exception->getPrevious() : $exception;
  32.         if ($nestedException instanceof BadCredentialsException) {
  33.             throw new UserPasswordInvalid();
  34.         }
  35.         if ($this->isCustomException($nestedException)){
  36.             throw $nestedException;
  37.         }
  38.         throw new AuthenticationFailedException($additionalInfo);
  39.     }
  40.     private function isCustomException(?\Exception $exception): bool
  41.     {
  42.         return $exception && in_array(get_class($exception), $this->customExceptionstrue);
  43.     }
  44. }