<?php
namespace App\EventSubscriber;
use App\Entity\Loginhistory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpFoundation\RequestStack;
class LoginSubscriber implements EventSubscriberInterface
{
private $em;
private $requestStack;
public function __construct(EntityManagerInterface $em, RequestStack $requestStack)
{
$this->em = $em;
$this->requestStack = $requestStack;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if (!is_object($user)) {
return;
}
$request = $this->requestStack->getCurrentRequest();
$ip = null;
if ($request !== null) {
$ip = $request->getClientIp();
}
$login = new Loginhistory();
$login->setLogintime(new \DateTime());
$login->setUsername($user->getUsername());
$login->setUserid((string)$user->getId());
$login->setUserip($ip);
$this->em->persist($login);
$this->em->flush();
}
public static function getSubscribedEvents()
{
return [
'security.interactive_login' => 'onSecurityInteractiveLogin',
];
}
}