vendor/symfony/security-http/Firewall/SwitchUserListener.php line 42

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Security\Http\Firewall;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  20. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  21. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  22. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  23. use Symfony\Component\Security\Core\Role\SwitchUserRole;
  24. use Symfony\Component\Security\Core\User\UserCheckerInterface;
  25. use Symfony\Component\Security\Core\User\UserInterface;
  26. use Symfony\Component\Security\Core\User\UserProviderInterface;
  27. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  28. use Symfony\Component\Security\Http\SecurityEvents;
  29. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  30. /**
  31.  * SwitchUserListener allows a user to impersonate another one temporarily
  32.  * (like the Unix su command).
  33.  *
  34.  * @author Fabien Potencier <fabien@symfony.com>
  35.  *
  36.  * @final since Symfony 4.3
  37.  */
  38. class SwitchUserListener implements ListenerInterface
  39. {
  40.     use LegacyListenerTrait;
  41.     const EXIT_VALUE '_exit';
  42.     private $tokenStorage;
  43.     private $provider;
  44.     private $userChecker;
  45.     private $providerKey;
  46.     private $accessDecisionManager;
  47.     private $usernameParameter;
  48.     private $role;
  49.     private $logger;
  50.     private $dispatcher;
  51.     private $stateless;
  52.     public function __construct(TokenStorageInterface $tokenStorageUserProviderInterface $providerUserCheckerInterface $userCheckerstring $providerKeyAccessDecisionManagerInterface $accessDecisionManagerLoggerInterface $logger nullstring $usernameParameter '_switch_user'string $role 'ROLE_ALLOWED_TO_SWITCH'EventDispatcherInterface $dispatcher nullbool $stateless false)
  53.     {
  54.         if (empty($providerKey)) {
  55.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  56.         }
  57.         $this->tokenStorage $tokenStorage;
  58.         $this->provider $provider;
  59.         $this->userChecker $userChecker;
  60.         $this->providerKey $providerKey;
  61.         $this->accessDecisionManager $accessDecisionManager;
  62.         $this->usernameParameter $usernameParameter;
  63.         $this->role $role;
  64.         $this->logger $logger;
  65.         $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  66.         $this->stateless $stateless;
  67.     }
  68.     /**
  69.      * Handles the switch to another user.
  70.      *
  71.      * @throws \LogicException if switching to a user failed
  72.      */
  73.     public function __invoke(RequestEvent $event)
  74.     {
  75.         $request $event->getRequest();
  76.         // usernames can be falsy
  77.         $username $request->get($this->usernameParameter);
  78.         if (null === $username || '' === $username) {
  79.             $username $request->headers->get($this->usernameParameter);
  80.         }
  81.         // if it's still "empty", nothing to do.
  82.         if (null === $username || '' === $username) {
  83.             return;
  84.         }
  85.         if (null === $this->tokenStorage->getToken()) {
  86.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  87.         }
  88.         if (self::EXIT_VALUE === $username) {
  89.             $this->tokenStorage->setToken($this->attemptExitUser($request));
  90.         } else {
  91.             try {
  92.                 $this->tokenStorage->setToken($this->attemptSwitchUser($request$username));
  93.             } catch (AuthenticationException $e) {
  94.                 throw new \LogicException(sprintf('Switch User failed: "%s"'$e->getMessage()));
  95.             }
  96.         }
  97.         if (!$this->stateless) {
  98.             $request->query->remove($this->usernameParameter);
  99.             $request->server->set('QUERY_STRING'http_build_query($request->query->all(), '''&'));
  100.             $response = new RedirectResponse($request->getUri(), 302);
  101.             $event->setResponse($response);
  102.         }
  103.     }
  104.     /**
  105.      * Attempts to switch to another user.
  106.      *
  107.      * @param Request $request  A Request instance
  108.      * @param string  $username
  109.      *
  110.      * @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
  111.      *
  112.      * @throws \LogicException
  113.      * @throws AccessDeniedException
  114.      */
  115.     private function attemptSwitchUser(Request $request$username)
  116.     {
  117.         $token $this->tokenStorage->getToken();
  118.         $originalToken $this->getOriginalToken($token);
  119.         if (null !== $originalToken) {
  120.             if ($token->getUsername() === $username) {
  121.                 return $token;
  122.             }
  123.             throw new \LogicException(sprintf('You are already switched to "%s" user.'$token->getUsername()));
  124.         }
  125.         $user $this->provider->loadUserByUsername($username);
  126.         if (false === $this->accessDecisionManager->decide($token, [$this->role], $user)) {
  127.             $exception = new AccessDeniedException();
  128.             $exception->setAttributes($this->role);
  129.             throw $exception;
  130.         }
  131.         if (null !== $this->logger) {
  132.             $this->logger->info('Attempting to switch to user.', ['username' => $username]);
  133.         }
  134.         $this->userChecker->checkPostAuth($user);
  135.         $roles $user->getRoles();
  136.         $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN'$this->tokenStorage->getToken(), false);
  137.         $token = new SwitchUserToken($user$user->getPassword(), $this->providerKey$roles$token);
  138.         if (null !== $this->dispatcher) {
  139.             $switchEvent = new SwitchUserEvent($request$token->getUser(), $token);
  140.             $this->dispatcher->dispatch($switchEventSecurityEvents::SWITCH_USER);
  141.             // use the token from the event in case any listeners have replaced it.
  142.             $token $switchEvent->getToken();
  143.         }
  144.         return $token;
  145.     }
  146.     /**
  147.      * Attempts to exit from an already switched user.
  148.      *
  149.      * @return TokenInterface The original TokenInterface instance
  150.      *
  151.      * @throws AuthenticationCredentialsNotFoundException
  152.      */
  153.     private function attemptExitUser(Request $request)
  154.     {
  155.         if (null === ($currentToken $this->tokenStorage->getToken()) || null === $original $this->getOriginalToken($currentToken)) {
  156.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  157.         }
  158.         if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
  159.             $user $this->provider->refreshUser($original->getUser());
  160.             $switchEvent = new SwitchUserEvent($request$user$original);
  161.             $this->dispatcher->dispatch($switchEventSecurityEvents::SWITCH_USER);
  162.             $original $switchEvent->getToken();
  163.         }
  164.         return $original;
  165.     }
  166.     private function getOriginalToken(TokenInterface $token): ?TokenInterface
  167.     {
  168.         if ($token instanceof SwitchUserToken) {
  169.             return $token->getOriginalToken();
  170.         }
  171.         foreach ($token->getRoles(false) as $role) {
  172.             if ($role instanceof SwitchUserRole) {
  173.                 return $role->getSource();
  174.             }
  175.         }
  176.         return null;
  177.     }
  178. }