<?php
namespace App\Security\Authentication;
use App\Model\InteractiveLoginUserInterface;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
class AuthenticationSubscriber implements EventSubscriberInterface
{
/** @var EntityManager */
private $em;
/**
* AuthenticationSubscriber constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function __destruct()
{
$this->em = null;
}
/**
* @codeCoverageIgnore
*
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
AuthenticationEvents::AUTHENTICATION_FAILURE => 'onAuthenticationFailure',
];
}
/**
* @param AuthenticationFailureEvent $event
*/
public function onAuthenticationFailure(AuthenticationFailureEvent $event): void
{
// TODO Add logging
}
/**
* @param InteractiveLoginEvent $event
*
* @throws \Doctrine\ORM\ORMException
*/
public function onInteractiveLogin(InteractiveLoginEvent $event): void
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof InteractiveLoginUserInterface) {
$user->setLastLoginAt(new \DateTime());
$user->setLastLoginFromIp($event->getRequest()->getClientIp());
$this->em->persist($user);
$this->em->flush();
$event->stopPropagation();
}
}
}