src/EventSubscriber/JwtAuthenticatorSubscriber.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Psr\Log\LoggerInterface;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Exception\UserNotFoundException;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  8. use Symfony\Component\Security\Http\Event\LoginFailureEvent;
  9. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  10. class JwtAuthenticatorSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var LoggerInterface
  14.      */
  15.     private $dbLogger;
  16.     public function __construct(LoggerInterface $dbLogger)
  17.     {
  18.         $this->dbLogger $dbLogger;
  19.     }
  20.     public function onLoginSuccess(LoginSuccessEvent $event)
  21.     {
  22.         if ('jwt_login' == $event->getFirewallName()) {
  23.             $roles $event->getUser()->getRoles();
  24.             $valid = (in_array('ROLE_API_USER'$roles) && (in_array('ROLE_PHONE'$roles) || in_array('ROLE_MAIL'$roles)));
  25.             if (!$valid) {
  26.                 $event->setResponse(new JsonResponse([
  27.                     'code' => 401,
  28.                     'message' => 'Érvénytelen hitelesítési információk.'
  29.                 ], 401
  30.                 ));
  31.             }
  32.             $this->dbLogger->info(sprintf("Sikeres API bejelentkezés: %s"$event->getUser()->getUserIdentifier()),
  33.                 [
  34.                     'clientIp' => $event->getRequest()->getClientIp()
  35.                 ]
  36.             );
  37.         }
  38.     }
  39.     public function onLoginFailure(LoginFailureEvent $event)
  40.     {
  41.         if ('jwt_login' == $event->getFirewallName()) {
  42.             $this->dbLogger->info(sprintf("Sikertelen API bejelentkezés!"),
  43.                 [
  44.                     'clientIp' => $event->getRequest()->getClientIp()
  45.                 ]
  46.             );
  47.         }
  48.     }
  49.     public static function getSubscribedEvents()
  50.     {
  51.         return [
  52.             LoginSuccessEvent::class => 'onLoginSuccess',
  53.             LoginFailureEvent::class => 'onLoginFailure'
  54.         ];
  55.     }
  56. }