<?php
namespace App\EventSubscriber;
use App\Entity\User;
use App\Entity\Enterprise;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
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 PasswordChangeSubscriber 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->isMasterRequest()) {
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;
}
//TODO: mettre la désactivation au service du monde en traduisant le tout.
if (($user->getRoles()[0]!=="ROLE_REGIONMANAGER" && $user->getRoles()[0]!=="ROLE_GESTIONNAIRE" && $user->getRoles()[0]!=="ROLE_ADMIN" && $user->getRoles()[0]!=="ROLE_BUSINESSLINEMANAGER"&& $user->getRoles()[0]!=="ROLE_GROUPMANAGER") ) {
$isDeactivate = true;
foreach($user->getContact()->getEnterpriseContactPositions() as $ecp){
if($ecp->getEnterprise()->getStatus() == true)
{
$isDeactivate = false;
}
}
}
if (!$user->getIsActive()) {
throw new AccessDeniedException('votre profil est désactivé');
}
// if it's not their first login, and they do not need to change their password, move on
if (!$user->getForcepasswordchange()) {
return;
}
// if we get here, it means we need to redirect them to the password change view.
$redirectTo = $this->urlGenerator->generate('changepassword');
if ($event->getRequest()->getRequestUri() !== $redirectTo) {
$event->setResponse(new RedirectResponse($redirectTo));
}
return;
}
}