SessionStorage.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Security\CSRF\TokenStorage;
  9. use OCP\ISession;
  10. /**
  11. * Class SessionStorage provides the session storage
  12. *
  13. * @package OC\Security\CSRF\TokenStorage
  14. */
  15. class SessionStorage {
  16. public function __construct(
  17. private ISession $session,
  18. ) {
  19. }
  20. public function setSession(ISession $session): void {
  21. $this->session = $session;
  22. }
  23. /**
  24. * Returns the current token or throws an exception if none is found.
  25. *
  26. * @throws \Exception
  27. */
  28. public function getToken(): string {
  29. $token = $this->session->get('requesttoken');
  30. if (empty($token)) {
  31. throw new \Exception('Session does not contain a requesttoken');
  32. }
  33. return $token;
  34. }
  35. /**
  36. * Set the valid current token to $value.
  37. */
  38. public function setToken(string $value): void {
  39. $this->session->set('requesttoken', $value);
  40. }
  41. /**
  42. * Removes the current token.
  43. */
  44. public function removeToken(): void {
  45. $this->session->remove('requesttoken');
  46. }
  47. /**
  48. * Whether the storage has a storage.
  49. */
  50. public function hasToken(): bool {
  51. return $this->session->exists('requesttoken');
  52. }
  53. }