<?php
namespace App\Controller;
use App\Builder\MailerBuilder;
use App\Form\User\CreateAccountType;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\Translation\TranslatorInterface;
class SecurityController extends AbstractController
{
private MailerBuilder $mailerBuilder;
public function __construct(MailerBuilder $mailerBuilder, TranslatorInterface $translator, RequestStack $requestStack, TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher)
{
$this->mailerBuilder = $mailerBuilder;
$this->translator = $translator;
$this->requestStack = $requestStack;
$this->tokenStorage = $tokenStorage;
$this->eventDispatcher = $eventDispatcher;
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
if ($this->getUser()) {
if (!$this->getUser()->getIsActive()) {
$this->addFlash('error', "Votre compte est inactif, veuillez prendre contact avec l'administrateur.");
$this->forceLogout();
return $this->redirectToRoute('login');
} else {
return $this->redirectToRoute('home');
}
} else {
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$formCreateAccount = $this->createForm(CreateAccountType::class)->handleRequest($request);
return $this->render(
'security/login.html.twig',
[
'last_username' => $lastUsername,
'error' => $error,
'formCreateAccount' => $formCreateAccount->createView(),
]
);
}
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
}
public function forceLogout(): void
{
$logoutEvent = new LogoutEvent($this->requestStack->getCurrentRequest(), $this->tokenStorage->getToken());
$this->eventDispatcher->dispatch($logoutEvent);
$this->tokenStorage->setToken(null);
$response = new Response();
$response->headers->clearCookie('REMEMBERME');
$response->send();
}
}