vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php line 39

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\EventDispatcherInterface;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  16. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  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. /**
  30.  * SwitchUserListener allows a user to impersonate another one temporarily
  31.  * (like the Unix su command).
  32.  *
  33.  * @author Fabien Potencier <fabien@symfony.com>
  34.  */
  35. class SwitchUserListener implements ListenerInterface
  36. {
  37.     const EXIT_VALUE '_exit';
  38.     private $tokenStorage;
  39.     private $provider;
  40.     private $userChecker;
  41.     private $providerKey;
  42.     private $accessDecisionManager;
  43.     private $usernameParameter;
  44.     private $role;
  45.     private $logger;
  46.     private $dispatcher;
  47.     private $stateless;
  48.     public function __construct(TokenStorageInterface $tokenStorageUserProviderInterface $providerUserCheckerInterface $userChecker$providerKeyAccessDecisionManagerInterface $accessDecisionManagerLoggerInterface $logger null$usernameParameter '_switch_user'$role 'ROLE_ALLOWED_TO_SWITCH'EventDispatcherInterface $dispatcher null$stateless false)
  49.     {
  50.         if (empty($providerKey)) {
  51.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  52.         }
  53.         $this->tokenStorage $tokenStorage;
  54.         $this->provider $provider;
  55.         $this->userChecker $userChecker;
  56.         $this->providerKey $providerKey;
  57.         $this->accessDecisionManager $accessDecisionManager;
  58.         $this->usernameParameter $usernameParameter;
  59.         $this->role $role;
  60.         $this->logger $logger;
  61.         $this->dispatcher $dispatcher;
  62.         $this->stateless $stateless;
  63.     }
  64.     /**
  65.      * Handles the switch to another user.
  66.      *
  67.      * @throws \LogicException if switching to a user failed
  68.      */
  69.     public function handle(GetResponseEvent $event)
  70.     {
  71.         $request $event->getRequest();
  72.         // usernames can be falsy
  73.         $username $request->get($this->usernameParameter);
  74.         if (null === $username || '' === $username) {
  75.             $username $request->headers->get($this->usernameParameter);
  76.         }
  77.         // if it's still "empty", nothing to do.
  78.         if (null === $username || '' === $username) {
  79.             return;
  80.         }
  81.         if (null === $this->tokenStorage->getToken()) {
  82.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  83.         }
  84.         if (self::EXIT_VALUE === $username) {
  85.             $this->tokenStorage->setToken($this->attemptExitUser($request));
  86.         } else {
  87.             try {
  88.                 $this->tokenStorage->setToken($this->attemptSwitchUser($request$username));
  89.             } catch (AuthenticationException $e) {
  90.                 throw new \LogicException('Switch User failed: '.$e->getMessage());
  91.             }
  92.         }
  93.         if (!$this->stateless) {
  94.             $request->query->remove($this->usernameParameter);
  95.             $request->server->set('QUERY_STRING'http_build_query($request->query->all(), '''&'));
  96.             $response = new RedirectResponse($request->getUri(), 302);
  97.             $event->setResponse($response);
  98.         }
  99.     }
  100.     /**
  101.      * Attempts to switch to another user.
  102.      *
  103.      * @param Request $request  A Request instance
  104.      * @param string  $username
  105.      *
  106.      * @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
  107.      *
  108.      * @throws \LogicException
  109.      * @throws AccessDeniedException
  110.      */
  111.     private function attemptSwitchUser(Request $request$username)
  112.     {
  113.         $token $this->tokenStorage->getToken();
  114.         $originalToken $this->getOriginalToken($token);
  115.         if (false !== $originalToken) {
  116.             if ($token->getUsername() === $username) {
  117.                 return $token;
  118.             }
  119.             // User already switched, exit before seamlessly switching to another user
  120.             $token $this->attemptExitUser($request);
  121.         }
  122.         if (false === $this->accessDecisionManager->decide($token, [$this->role])) {
  123.             $exception = new AccessDeniedException();
  124.             $exception->setAttributes($this->role);
  125.             throw $exception;
  126.         }
  127.         if (null !== $this->logger) {
  128.             $this->logger->info('Attempting to switch to user.', ['username' => $username]);
  129.         }
  130.         $user $this->provider->loadUserByUsername($username);
  131.         $this->userChecker->checkPostAuth($user);
  132.         $roles $user->getRoles();
  133.         $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN'$token);
  134.         $token = new UsernamePasswordToken($user$user->getPassword(), $this->providerKey$roles);
  135.         if (null !== $this->dispatcher) {
  136.             $switchEvent = new SwitchUserEvent($request$token->getUser(), $token);
  137.             $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER$switchEvent);
  138.             // use the token from the event in case any listeners have replaced it.
  139.             $token $switchEvent->getToken();
  140.         }
  141.         return $token;
  142.     }
  143.     /**
  144.      * Attempts to exit from an already switched user.
  145.      *
  146.      * @return TokenInterface The original TokenInterface instance
  147.      *
  148.      * @throws AuthenticationCredentialsNotFoundException
  149.      */
  150.     private function attemptExitUser(Request $request)
  151.     {
  152.         if (false === $original $this->getOriginalToken($this->tokenStorage->getToken())) {
  153.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  154.         }
  155.         if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
  156.             $user $this->provider->refreshUser($original->getUser());
  157.             $switchEvent = new SwitchUserEvent($request$user$original);
  158.             $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER$switchEvent);
  159.             $original $switchEvent->getToken();
  160.         }
  161.         return $original;
  162.     }
  163.     /**
  164.      * Gets the original Token from a switched one.
  165.      *
  166.      * @return TokenInterface|false The original TokenInterface instance, false if the current TokenInterface is not switched
  167.      */
  168.     private function getOriginalToken(TokenInterface $token)
  169.     {
  170.         foreach ($token->getRoles() as $role) {
  171.             if ($role instanceof SwitchUserRole) {
  172.                 return $role->getSource();
  173.             }
  174.         }
  175.         return false;
  176.     }
  177. }