SessionTokenStorage.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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\Csrf\TokenStorage;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  12. use Symfony\Component\Security\Csrf\Exception\TokenNotFoundException;
  13. /**
  14. * Token storage that uses a Symfony Session object.
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class SessionTokenStorage implements ClearableTokenStorageInterface
  19. {
  20. /**
  21. * The namespace used to store values in the session.
  22. */
  23. public const SESSION_NAMESPACE = '_csrf';
  24. private $session;
  25. private $namespace;
  26. /**
  27. * Initializes the storage with a Session object and a session namespace.
  28. *
  29. * @param string $namespace The namespace under which the token is stored in the session
  30. */
  31. public function __construct(SessionInterface $session, string $namespace = self::SESSION_NAMESPACE)
  32. {
  33. $this->session = $session;
  34. $this->namespace = $namespace;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function getToken(string $tokenId)
  40. {
  41. if (!$this->session->isStarted()) {
  42. $this->session->start();
  43. }
  44. if (!$this->session->has($this->namespace.'/'.$tokenId)) {
  45. throw new TokenNotFoundException('The CSRF token with ID '.$tokenId.' does not exist.');
  46. }
  47. return (string) $this->session->get($this->namespace.'/'.$tokenId);
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function setToken(string $tokenId, string $token)
  53. {
  54. if (!$this->session->isStarted()) {
  55. $this->session->start();
  56. }
  57. $this->session->set($this->namespace.'/'.$tokenId, $token);
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function hasToken(string $tokenId)
  63. {
  64. if (!$this->session->isStarted()) {
  65. $this->session->start();
  66. }
  67. return $this->session->has($this->namespace.'/'.$tokenId);
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. public function removeToken(string $tokenId)
  73. {
  74. if (!$this->session->isStarted()) {
  75. $this->session->start();
  76. }
  77. return $this->session->remove($this->namespace.'/'.$tokenId);
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function clear()
  83. {
  84. foreach (array_keys($this->session->all()) as $key) {
  85. if (0 === strpos($key, $this->namespace.'/')) {
  86. $this->session->remove($key);
  87. }
  88. }
  89. }
  90. }