<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AuthenticationPostListener implements EventSubscriberInterface
{
private $security;
private $router;
private $tokenStorage;
public function __construct(Security $security, RouterInterface $router, TokenStorageInterface $tokenStorage)
{
$this->security = $security;
$this->router = $router;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 5]
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
//dump($request->getPathInfo());
//exit;
if (in_array($request->getPathInfo(), ['/login', '/login_check', '/reinitialize', '/logout'])) {
// Skip checks for these paths
return;
}
$token = $this->tokenStorage->getToken();
if ($token && $this->security->isGranted('IS_AUTHENTICATED_FULLY')) {
$user = $token->getUser();
// Check for password expiration or any other condition
if ($this->hasPasswordExpired($user->getDateMajMdp())) {
$response = new RedirectResponse($this->router->generate('ctsweb_front_login'));
$event->setResponse($response);
return;
}
}
}
public function hasPasswordExpired(\DateTime $passwordUpdateDate) {
$interval = date_interval_create_from_date_string("90 days");
$passwordUpdateDate = $passwordUpdateDate->format('Y-m-d H:i:s');
$expirationDate = date_add(new \DateTime($passwordUpdateDate), $interval);
$dateNow = (new \DateTime())->setTimezone(new \DateTimeZone('Europe/Paris'));
return $expirationDate < $dateNow;
}
}