ImpersonateUrlGenerator.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Impersonate;
  11. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  15. use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
  16. /**
  17. * Provides generator functions for the impersonate url exit.
  18. *
  19. * @author Amrouche Hamza <hamza.simperfit@gmail.com>
  20. * @author Damien Fayet <damienf1521@gmail.com>
  21. */
  22. class ImpersonateUrlGenerator
  23. {
  24. private $requestStack;
  25. private $tokenStorage;
  26. private $firewallMap;
  27. public function __construct(RequestStack $requestStack, FirewallMap $firewallMap, TokenStorageInterface $tokenStorage)
  28. {
  29. $this->requestStack = $requestStack;
  30. $this->tokenStorage = $tokenStorage;
  31. $this->firewallMap = $firewallMap;
  32. }
  33. public function generateExitPath(string $targetUri = null): string
  34. {
  35. return $this->buildExitPath($targetUri);
  36. }
  37. public function generateExitUrl(string $targetUri = null): string
  38. {
  39. if (null === $request = $this->requestStack->getCurrentRequest()) {
  40. return '';
  41. }
  42. return $request->getUriForPath($this->buildExitPath($targetUri));
  43. }
  44. private function isImpersonatedUser(): bool
  45. {
  46. return $this->tokenStorage->getToken() instanceof SwitchUserToken;
  47. }
  48. private function buildExitPath(string $targetUri = null): string
  49. {
  50. if (null === ($request = $this->requestStack->getCurrentRequest()) || !$this->isImpersonatedUser()) {
  51. return '';
  52. }
  53. if (null === $switchUserConfig = $this->firewallMap->getFirewallConfig($request)->getSwitchUser()) {
  54. throw new \LogicException('Unable to generate the impersonate exit URL without a firewall configured for the user switch.');
  55. }
  56. if (null === $targetUri) {
  57. $targetUri = $request->getRequestUri();
  58. }
  59. $targetUri .= (parse_url($targetUri, \PHP_URL_QUERY) ? '&' : '?').http_build_query([$switchUserConfig['parameter'] => SwitchUserListener::EXIT_VALUE]);
  60. return $targetUri;
  61. }
  62. }