<?php
namespace App\Controller\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use DateTimeImmutable;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use App\Service\SwitchUserTokenService;
class SecurityController extends AbstractController
{
public function __construct(private SwitchUserTokenService $switchUserTokenService)
{
$this->switchUserTokenService = $switchUserTokenService;
}
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('app_home');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('authentication/sign-in.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route('/switch-user', name: 'app_switch_user')]
public function switchUser(Request $request, EventDispatcherInterface $eventDispatcher, Session $session)
{
$token = $request->query->get('token');
$userId = $request->query->get('user_id');
$tokenObj = $this->switchUserTokenService->fetchToken($token, $userId);
if ($tokenObj and $tokenObj->getExpiredAt() > new DateTimeImmutable()) {
$authToken = new UsernamePasswordToken($tokenObj->getUser(), "main", $tokenObj->getUser()->getRoles());
$this->container->get("security.token_storage")->setToken($authToken);
$event = new InteractiveLoginEvent($request, $authToken);
$eventDispatcher->dispatch($event, "security.interactive_login");
$session->set('_switch_token', $token);
return $this->redirectToRoute('app_home');
}
throw new BadRequestException('Jeton invalide !');
}
}