SessionStorage.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Security\CSRF\TokenStorage;
  27. use OCP\ISession;
  28. /**
  29. * Class SessionStorage provides the session storage
  30. *
  31. * @package OC\Security\CSRF\TokenStorage
  32. */
  33. class SessionStorage {
  34. /** @var ISession */
  35. private $session;
  36. /**
  37. * @param ISession $session
  38. */
  39. public function __construct(ISession $session) {
  40. $this->session = $session;
  41. }
  42. /**
  43. * @param ISession $session
  44. */
  45. public function setSession(ISession $session) {
  46. $this->session = $session;
  47. }
  48. /**
  49. * Returns the current token or throws an exception if none is found.
  50. *
  51. * @return string
  52. * @throws \Exception
  53. */
  54. public function getToken(): string {
  55. $token = $this->session->get('requesttoken');
  56. if (empty($token)) {
  57. throw new \Exception('Session does not contain a requesttoken');
  58. }
  59. return $token;
  60. }
  61. /**
  62. * Set the valid current token to $value.
  63. *
  64. * @param string $value
  65. */
  66. public function setToken(string $value) {
  67. $this->session->set('requesttoken', $value);
  68. }
  69. /**
  70. * Removes the current token.
  71. */
  72. public function removeToken() {
  73. $this->session->remove('requesttoken');
  74. }
  75. /**
  76. * Whether the storage has a storage.
  77. *
  78. * @return bool
  79. */
  80. public function hasToken(): bool {
  81. return $this->session->exists('requesttoken');
  82. }
  83. }