src/EventSubscriber/JwtSubscriber.php line 42

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\Main\UserRepository;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
  6. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
  7. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
  8. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
  9. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Exception\HttpException;
  12. use Symfony\Contracts\Translation\TranslatorInterface;
  13. class JwtSubscriber implements EventSubscriberInterface
  14. {
  15.     protected $entityManager;
  16.     protected $userRepository;
  17.     protected $translator;
  18.     public function __construct(EntityManagerInterface $entityManagerUserRepository $userRepositoryTranslatorInterface $translator)
  19.     {
  20.         $this->entityManager $entityManager;
  21.         $this->userRepository $userRepository;
  22.         $this->translator $translator;
  23.     }
  24.     public function onExpired(JWTExpiredEvent $event)
  25.     {
  26.         throw new HttpException(401,'Expired JWT Token');
  27.     }
  28.     public function onNotFound(JWTNotFoundEvent $event)
  29.     {
  30.         $message $event->getException()->getPrevious()->getMessage();
  31.         throw new HttpException(403$message);
  32.     }
  33.     public function onInvalid(JWTInvalidEvent $event)
  34.     {
  35.         $message $event->getException()->getPrevious()->getMessage();
  36.         throw new HttpException(401$message);
  37.     }
  38.     public function onAuthenticationFailure(AuthenticationFailureEvent $event)
  39.     {
  40. //        $message = $event->getException()->getPrevious()->getMessage();
  41.         throw new HttpException(401$this->translator->trans('USERNAME_OR_PASSWORD_ARE_INCORRECT'));
  42.     }
  43.     public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
  44.     {
  45.         //
  46.     }
  47.     public static function getSubscribedEvents()
  48.     {
  49.         return [
  50.             'lexik_jwt_authentication.on_jwt_not_found' => 'onNotFound',
  51.             'lexik_jwt_authentication.on_jwt_expired' => 'onExpired',
  52.             'lexik_jwt_authentication.on_jwt_invalid' => 'onInvalid',
  53.             'lexik_jwt_authentication.on_authentication_failure' => 'onAuthenticationFailure',
  54.             'lexik_jwt_authentication.on_authentication_success' => 'onAuthenticationSuccess',
  55.         ];
  56.     }
  57. }