vendor/symfony/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 $userCheckerstring $providerKeyAccessDecisionManagerInterface $accessDecisionManagerLoggerInterface $logger nullstring $usernameParameter '_switch_user'string $role 'ROLE_ALLOWED_TO_SWITCH'EventDispatcherInterface $dispatcher nullbool $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.         $username $request->get($this->usernameParameter) ?: $request->headers->get($this->usernameParameter);
  73.         if (!$username) {
  74.             return;
  75.         }
  76.         if (null === $this->tokenStorage->getToken()) {
  77.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  78.         }
  79.         if (self::EXIT_VALUE === $username) {
  80.             $this->tokenStorage->setToken($this->attemptExitUser($request));
  81.         } else {
  82.             try {
  83.                 $this->tokenStorage->setToken($this->attemptSwitchUser($request$username));
  84.             } catch (AuthenticationException $e) {
  85.                 throw new \LogicException(sprintf('Switch User failed: "%s"'$e->getMessage()));
  86.             }
  87.         }
  88.         if (!$this->stateless) {
  89.             $request->query->remove($this->usernameParameter);
  90.             $request->server->set('QUERY_STRING'http_build_query($request->query->all(), '''&'));
  91.             $response = new RedirectResponse($request->getUri(), 302);
  92.             $event->setResponse($response);
  93.         }
  94.     }
  95.     /**
  96.      * Attempts to switch to another user.
  97.      *
  98.      * @param Request $request  A Request instance
  99.      * @param string  $username
  100.      *
  101.      * @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
  102.      *
  103.      * @throws \LogicException
  104.      * @throws AccessDeniedException
  105.      */
  106.     private function attemptSwitchUser(Request $request$username)
  107.     {
  108.         $token $this->tokenStorage->getToken();
  109.         $originalToken $this->getOriginalToken($token);
  110.         if (false !== $originalToken) {
  111.             if ($token->getUsername() === $username) {
  112.                 return $token;
  113.             }
  114.             throw new \LogicException(sprintf('You are already switched to "%s" user.'$token->getUsername()));
  115.         }
  116.         $user $this->provider->loadUserByUsername($username);
  117.         if (false === $this->accessDecisionManager->decide($token, [$this->role], $user)) {
  118.             $exception = new AccessDeniedException();
  119.             $exception->setAttributes($this->role);
  120.             throw $exception;
  121.         }
  122.         if (null !== $this->logger) {
  123.             $this->logger->info('Attempting to switch to user.', ['username' => $username]);
  124.         }
  125.         $this->userChecker->checkPostAuth($user);
  126.         $roles $user->getRoles();
  127.         $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN'$this->tokenStorage->getToken());
  128.         $token = new UsernamePasswordToken($user$user->getPassword(), $this->providerKey$roles);
  129.         if (null !== $this->dispatcher) {
  130.             $switchEvent = new SwitchUserEvent($request$token->getUser(), $token);
  131.             $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER$switchEvent);
  132.             // use the token from the event in case any listeners have replaced it.
  133.             $token $switchEvent->getToken();
  134.         }
  135.         return $token;
  136.     }
  137.     /**
  138.      * Attempts to exit from an already switched user.
  139.      *
  140.      * @return TokenInterface The original TokenInterface instance
  141.      *
  142.      * @throws AuthenticationCredentialsNotFoundException
  143.      */
  144.     private function attemptExitUser(Request $request)
  145.     {
  146.         if (false === $original $this->getOriginalToken($this->tokenStorage->getToken())) {
  147.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  148.         }
  149.         if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
  150.             $user $this->provider->refreshUser($original->getUser());
  151.             $switchEvent = new SwitchUserEvent($request$user$original);
  152.             $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER$switchEvent);
  153.             $original $switchEvent->getToken();
  154.         }
  155.         return $original;
  156.     }
  157.     /**
  158.      * Gets the original Token from a switched one.
  159.      *
  160.      * @return TokenInterface|false The original TokenInterface instance, false if the current TokenInterface is not switched
  161.      */
  162.     private function getOriginalToken(TokenInterface $token)
  163.     {
  164.         foreach ($token->getRoles() as $role) {
  165.             if ($role instanceof SwitchUserRole) {
  166.                 return $role->getSource();
  167.             }
  168.         }
  169.         return false;
  170.     }
  171. }