From 9820b2c4747693e037b46f6434826dfdb6007a5f Mon Sep 17 00:00:00 2001 From: NGUEREZA Tony Date: Thu, 2 Nov 2023 05:48:10 +0100 Subject: [PATCH] Add CSRF Manager support to return token query --- src/Security/Csrf/CsrfManager.php | 16 ++++++++++++++++ tests/Security/Csrf/CsrfManagerTest.php | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/Security/Csrf/CsrfManager.php b/src/Security/Csrf/CsrfManager.php index 40d0d3a..50d2a82 100644 --- a/src/Security/Csrf/CsrfManager.php +++ b/src/Security/Csrf/CsrfManager.php @@ -149,6 +149,22 @@ public function getToken(?string $key = null): string return $value; } + /** + * Return the token query to be used in query string + * @param string|null $key + * @return array + */ + public function getTokenQuery(?string $key = null): array + { + $token = $this->getToken($key); + + if ($key === null) { + $key = $this->getConfigValue('key'); + } + + return [$key => $token]; + } + /** * Clear all CSRF data from storage * @return void diff --git a/tests/Security/Csrf/CsrfManagerTest.php b/tests/Security/Csrf/CsrfManagerTest.php index cdced17..21b57be 100644 --- a/tests/Security/Csrf/CsrfManagerTest.php +++ b/tests/Security/Csrf/CsrfManagerTest.php @@ -159,4 +159,23 @@ public function testValidateIsUnique(): void $o->clear(); $this->assertNull($storage->get('csrf_key')); } + + public function testGetTokenQuery(): void + { + $storage = new CsrfNullStorage(); + $storage->set('csrf_key', 'bar', time() + 1000); + $config = $this->getMockInstance(Config::class, [ + 'get' => [ + 'key' => 'csrf_key', + 'expire' => 600, + ] + ]); + + $o = new CsrfManager($config, $storage); + + $queries = $o->getTokenQuery(); + $this->assertCount(1, $queries); + $this->assertArrayHasKey('csrf_key', $queries); + $this->assertEquals('bar', $queries['csrf_key']); + } }