← Back
Editing: ImpersonatorExceptionListener.php
<?php namespace App\EventListener; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\Event\SwitchUserEvent; use Symfony\Component\Security\Http\SecurityEvents; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class ImpersonatorExceptionListener { public function __construct( private readonly Security $security, private readonly UserProviderInterface $provider, private readonly RequestStack $requestStack, private readonly ?EventDispatcherInterface $dispatcher, private readonly TokenStorageInterface $tokenStorage ) { } public function onKernelException(ExceptionEvent $event) { $exception = $event->getThrowable(); if (!$exception instanceof AccessDeniedHttpException) { return; } $token = $this->security->getToken(); if (!$token instanceof SwitchUserToken) { return; } $request = $this->requestStack->getMainRequest(); $originalToken = $token->getOriginalToken(); $user = $this->provider->refreshUser($originalToken->getUser()); $originalToken->setUser($user); $switchEvent = new SwitchUserEvent($request, $user, $originalToken); $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER); $this->tokenStorage->setToken($switchEvent->getToken()); $response = new RedirectResponse($request->getUri()); $event->setResponse($response); } }
Save File
Cancel