src/Security/Authentication/AuthenticationSubscriber.php line 50

Open in your IDE?
  1. <?php
  2. namespace App\Security\Authentication;
  3. use App\Model\InteractiveLoginUserInterface;
  4. use Doctrine\ORM\EntityManager;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Security\Core\AuthenticationEvents;
  8. use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
  9. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  10. use Symfony\Component\Security\Http\SecurityEvents;
  11. class AuthenticationSubscriber implements EventSubscriberInterface
  12. {
  13.     /** @var EntityManager */
  14.     private $em;
  15.     /**
  16.      * AuthenticationSubscriber constructor.
  17.      *
  18.      * @param EntityManagerInterface $em
  19.      */
  20.     public function __construct(EntityManagerInterface $em)
  21.     {
  22.         $this->em $em;
  23.     }
  24.     public function __destruct()
  25.     {
  26.         $this->em null;
  27.     }
  28.     /**
  29.      * @codeCoverageIgnore
  30.      *
  31.      * @return array
  32.      */
  33.     public static function getSubscribedEvents(): array
  34.     {
  35.         return [
  36.             SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
  37.             AuthenticationEvents::AUTHENTICATION_FAILURE => 'onAuthenticationFailure',
  38.         ];
  39.     }
  40.     /**
  41.      * @param AuthenticationFailureEvent $event
  42.      */
  43.     public function onAuthenticationFailure(AuthenticationFailureEvent $event): void
  44.     {
  45.         // TODO Add logging
  46.     }
  47.     /**
  48.      * @param InteractiveLoginEvent $event
  49.      *
  50.      * @throws \Doctrine\ORM\ORMException
  51.      */
  52.     public function onInteractiveLogin(InteractiveLoginEvent $event): void
  53.     {
  54.         $user $event->getAuthenticationToken()->getUser();
  55.         if ($user instanceof InteractiveLoginUserInterface) {
  56.             $user->setLastLoginAt(new \DateTime());
  57.             $user->setLastLoginFromIp($event->getRequest()->getClientIp());
  58.             $this->em->persist($user);
  59.             $this->em->flush();
  60.             $event->stopPropagation();
  61.         }
  62.     }
  63. }