<?php
namespace App\EventSubscriber;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class PasswordExpirationManager implements EventSubscriberInterface
{
private $security;
private $urlGenerator;
public function __construct(Security $security, UrlGeneratorInterface $urlGenerator)
{
$this->security = $security;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['forcePasswordChange', 0]
],
];
}
public function forcePasswordChange(RequestEvent $event): void
{
// only deal with the main request, disregard subrequests
if (!$event->isMainRequest()) {
return;
}
$user = $this->security->getUser();
// if you do not have a valid user, it means it's not an authenticated request, so it's not our concern
if (!$user instanceof User) {
return;
}
// if it's not their first login, and they do not need to change their password, move on
$now_date = strtotime(date("Y-m-d H:i:s"));
$pastChange_date = strtotime($user->getLastPasswordChange());
//dd($pastChange_date);
$timePassed = abs($now_date - $pastChange_date)/(60 * 60 * 24);
//dd($timePassed);
if ($user->getForcePasswordChange() == 1 && $timePassed < 90) {
return;
}
// if we get here, it means we need to redirect them to the password change view.
$redirectTo = $this->urlGenerator->generate('app_reset_password_no_token');
if ($event->getRequest()->getRequestUri() != $redirectTo){
$event->setResponse(new RedirectResponse($redirectTo));
}
return;
}
}