CsrfTokenManager.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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;
  9. use OC\Security\CSRF\TokenStorage\SessionStorage;
  10. /**
  11. * Class CsrfTokenManager is the manager for all CSRF token related activities.
  12. *
  13. * @package OC\Security\CSRF
  14. */
  15. class CsrfTokenManager {
  16. private SessionStorage $sessionStorage;
  17. private ?CsrfToken $csrfToken = null;
  18. public function __construct(
  19. private CsrfTokenGenerator $tokenGenerator,
  20. SessionStorage $storageInterface,
  21. ) {
  22. $this->sessionStorage = $storageInterface;
  23. }
  24. /**
  25. * Returns the current CSRF token, if none set it will create a new one.
  26. */
  27. public function getToken(): CsrfToken {
  28. if (!\is_null($this->csrfToken)) {
  29. return $this->csrfToken;
  30. }
  31. if ($this->sessionStorage->hasToken()) {
  32. $value = $this->sessionStorage->getToken();
  33. } else {
  34. $value = $this->tokenGenerator->generateToken();
  35. $this->sessionStorage->setToken($value);
  36. }
  37. $this->csrfToken = new CsrfToken($value);
  38. return $this->csrfToken;
  39. }
  40. /**
  41. * Invalidates any current token and sets a new one.
  42. */
  43. public function refreshToken(): CsrfToken {
  44. $value = $this->tokenGenerator->generateToken();
  45. $this->sessionStorage->setToken($value);
  46. $this->csrfToken = new CsrfToken($value);
  47. return $this->csrfToken;
  48. }
  49. /**
  50. * Remove the current token from the storage.
  51. */
  52. public function removeToken(): void {
  53. $this->csrfToken = null;
  54. $this->sessionStorage->removeToken();
  55. }
  56. /**
  57. * Verifies whether the provided token is valid.
  58. */
  59. public function isTokenValid(CsrfToken $token): bool {
  60. if (!$this->sessionStorage->hasToken()) {
  61. return false;
  62. }
  63. return hash_equals(
  64. $this->sessionStorage->getToken(),
  65. $token->getDecryptedValue()
  66. );
  67. }
  68. }