/RestAPI/vendor/symfony/security/Http/Firewall/ContextListener.php

https://gitlab.com/martinstti/silex-microframework-rest · PHP · 176 lines · 114 code · 28 blank · 34 comment · 20 complexity · 99e37f9188d6fd372cd80a3ef7dceeea MD5 · raw file

  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\HttpKernel\Event\GetResponseEvent;
  13. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
  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\Exception\UsernameNotFoundException;
  19. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  20. use Symfony\Component\Security\Core\User\UserInterface;
  21. use Symfony\Component\Security\Core\User\UserProviderInterface;
  22. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  23. /**
  24. * ContextListener manages the SecurityContext persistence through a session.
  25. *
  26. * @author Fabien Potencier <fabien@symfony.com>
  27. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  28. */
  29. class ContextListener implements ListenerInterface
  30. {
  31. private $tokenStorage;
  32. private $contextKey;
  33. private $sessionKey;
  34. private $logger;
  35. private $userProviders;
  36. private $dispatcher;
  37. private $registered;
  38. public function __construct(TokenStorageInterface $tokenStorage, array $userProviders, $contextKey, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null)
  39. {
  40. if (empty($contextKey)) {
  41. throw new \InvalidArgumentException('$contextKey must not be empty.');
  42. }
  43. foreach ($userProviders as $userProvider) {
  44. if (!$userProvider instanceof UserProviderInterface) {
  45. throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "Symfony\Component\Security\Core\User\UserProviderInterface".', get_class($userProvider)));
  46. }
  47. }
  48. $this->tokenStorage = $tokenStorage;
  49. $this->userProviders = $userProviders;
  50. $this->contextKey = $contextKey;
  51. $this->sessionKey = '_security_'.$contextKey;
  52. $this->logger = $logger;
  53. $this->dispatcher = $dispatcher;
  54. }
  55. /**
  56. * Reads the Security Token from the session.
  57. *
  58. * @param GetResponseEvent $event A GetResponseEvent instance
  59. */
  60. public function handle(GetResponseEvent $event)
  61. {
  62. if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) {
  63. $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
  64. $this->registered = true;
  65. }
  66. $request = $event->getRequest();
  67. $session = $request->hasPreviousSession() ? $request->getSession() : null;
  68. if (null === $session || null === $token = $session->get($this->sessionKey)) {
  69. $this->tokenStorage->setToken(null);
  70. return;
  71. }
  72. $token = unserialize($token);
  73. if (null !== $this->logger) {
  74. $this->logger->debug('Read existing security token from the session.', array('key' => $this->sessionKey));
  75. }
  76. if ($token instanceof TokenInterface) {
  77. $token = $this->refreshUser($token);
  78. } elseif (null !== $token) {
  79. if (null !== $this->logger) {
  80. $this->logger->warning('Expected a security token from the session, got something else.', array('key' => $this->sessionKey, 'received' => $token));
  81. }
  82. $token = null;
  83. }
  84. $this->tokenStorage->setToken($token);
  85. }
  86. /**
  87. * Writes the security token into the session.
  88. *
  89. * @param FilterResponseEvent $event A FilterResponseEvent instance
  90. */
  91. public function onKernelResponse(FilterResponseEvent $event)
  92. {
  93. if (!$event->isMasterRequest()) {
  94. return;
  95. }
  96. if (!$event->getRequest()->hasSession()) {
  97. return;
  98. }
  99. $this->dispatcher->removeListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
  100. $this->registered = false;
  101. $request = $event->getRequest();
  102. $session = $request->getSession();
  103. if ((null === $token = $this->tokenStorage->getToken()) || ($token instanceof AnonymousToken)) {
  104. if ($request->hasPreviousSession()) {
  105. $session->remove($this->sessionKey);
  106. }
  107. } else {
  108. $session->set($this->sessionKey, serialize($token));
  109. if (null !== $this->logger) {
  110. $this->logger->debug('Stored the security token in the session.', array('key' => $this->sessionKey));
  111. }
  112. }
  113. }
  114. /**
  115. * Refreshes the user by reloading it from the user provider.
  116. *
  117. * @param TokenInterface $token
  118. *
  119. * @return TokenInterface|null
  120. *
  121. * @throws \RuntimeException
  122. */
  123. protected function refreshUser(TokenInterface $token)
  124. {
  125. $user = $token->getUser();
  126. if (!$user instanceof UserInterface) {
  127. return $token;
  128. }
  129. foreach ($this->userProviders as $provider) {
  130. try {
  131. $refreshedUser = $provider->refreshUser($user);
  132. $token->setUser($refreshedUser);
  133. if (null !== $this->logger) {
  134. $this->logger->debug('User was reloaded from a user provider.', array('username' => $refreshedUser->getUsername(), 'provider' => get_class($provider)));
  135. }
  136. return $token;
  137. } catch (UnsupportedUserException $e) {
  138. // let's try the next user provider
  139. } catch (UsernameNotFoundException $e) {
  140. if (null !== $this->logger) {
  141. $this->logger->warning('Username could not be found in the selected user provider.', array('username' => $e->getUsername(), 'provider' => get_class($provider)));
  142. }
  143. return;
  144. }
  145. }
  146. throw new \RuntimeException(sprintf('There is no user provider for user "%s".', get_class($user)));
  147. }
  148. }