SessionStorage.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. public function __construct(
  35. private ISession $session,
  36. ) {
  37. }
  38. public function setSession(ISession $session): void {
  39. $this->session = $session;
  40. }
  41. /**
  42. * Returns the current token or throws an exception if none is found.
  43. *
  44. * @throws \Exception
  45. */
  46. public function getToken(): string {
  47. $token = $this->session->get('requesttoken');
  48. if (empty($token)) {
  49. throw new \Exception('Session does not contain a requesttoken');
  50. }
  51. return $token;
  52. }
  53. /**
  54. * Set the valid current token to $value.
  55. */
  56. public function setToken(string $value): void {
  57. $this->session->set('requesttoken', $value);
  58. }
  59. /**
  60. * Removes the current token.
  61. */
  62. public function removeToken(): void {
  63. $this->session->remove('requesttoken');
  64. }
  65. /**
  66. * Whether the storage has a storage.
  67. */
  68. public function hasToken(): bool {
  69. return $this->session->exists('requesttoken');
  70. }
  71. }