src/EventListener/LoginHistoryListener.php line 19
<?php
namespace App\EventListener;
use App\Entity\LoginHistory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\Event\LogoutEvent;
class LoginHistoryListener
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
// Get the user who logged in
$user = $event->getAuthenticationToken()->getUser();
// Create a new LoginHistory entry
$loginHistory = new LoginHistory();
$loginHistory->setUser($user);
$loginHistory->setLoginAt(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));
// Persist the LoginHistory entry
$this->entityManager->persist($loginHistory);
$this->entityManager->flush();
}
public function onLogout(LogoutEvent $event)
{
// Get the user who logged out
$user = $event->getToken()->getUser();
// Find the most recent LoginHistory entry for the user
$loginHistory = $this->entityManager->getRepository(LoginHistory::class)->findOneBy(
['user' => $user],
['loginAt' => 'DESC']
);
if ($loginHistory) {
// Update the Logout timestamp
$loginHistory->setLogoutAt(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));
$this->entityManager->flush();
}
}
}