FirewallAwareLoginLinkHandler.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\Bundle\SecurityBundle\LoginLink;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\Security\Core\User\UserInterface;
  16. use Symfony\Component\Security\Http\LoginLink\LoginLinkDetails;
  17. use Symfony\Component\Security\Http\LoginLink\LoginLinkHandlerInterface;
  18. /**
  19. * Decorates the login link handler for the current firewall.
  20. *
  21. * @author Ryan Weaver <ryan@symfonycasts.com>
  22. */
  23. class FirewallAwareLoginLinkHandler implements LoginLinkHandlerInterface
  24. {
  25. private $firewallMap;
  26. private $loginLinkHandlerLocator;
  27. private $requestStack;
  28. public function __construct(FirewallMap $firewallMap, ContainerInterface $loginLinkHandlerLocator, RequestStack $requestStack)
  29. {
  30. $this->firewallMap = $firewallMap;
  31. $this->loginLinkHandlerLocator = $loginLinkHandlerLocator;
  32. $this->requestStack = $requestStack;
  33. }
  34. public function createLoginLink(UserInterface $user): LoginLinkDetails
  35. {
  36. return $this->getLoginLinkHandler()->createLoginLink($user);
  37. }
  38. public function consumeLoginLink(Request $request): UserInterface
  39. {
  40. return $this->getLoginLinkHandler()->consumeLoginLink($request);
  41. }
  42. private function getLoginLinkHandler(): LoginLinkHandlerInterface
  43. {
  44. if (null === $request = $this->requestStack->getCurrentRequest()) {
  45. throw new \LogicException('Cannot determine the correct LoginLinkHandler to use: there is no active Request and so, the firewall cannot be determined. Try using the specific login link handler service.');
  46. }
  47. $firewall = $this->firewallMap->getFirewallConfig($request);
  48. if (!$firewall) {
  49. throw new \LogicException('No login link handler found as the current route is not covered by a firewall.');
  50. }
  51. $firewallName = $firewall->getName();
  52. if (!$this->loginLinkHandlerLocator->has($firewallName)) {
  53. throw new \LogicException(sprintf('No login link handler found. Did you add a login_link key under your "%s" firewall?', $firewallName));
  54. }
  55. return $this->loginLinkHandlerLocator->get($firewallName);
  56. }
  57. }