From 5025c338345b4d564df3d6c9c55c034d51e5333d Mon Sep 17 00:00:00 2001 From: michalsn Date: Sat, 28 Sep 2019 08:05:27 +0200 Subject: [PATCH] Add csrf_header() and csrf_meta() helper functions --- system/Common.php | 36 +++++++++++++++++++ tests/system/CommonFunctionsTest.php | 10 ++++++ .../source/general/common_functions.rst | 16 +++++++++ 3 files changed, 62 insertions(+) diff --git a/system/Common.php b/system/Common.php index 85f2a765bb..ce6fbd0bc3 100644 --- a/system/Common.php +++ b/system/Common.php @@ -723,6 +723,25 @@ if (! function_exists('csrf_token')) //-------------------------------------------------------------------- +if (! function_exists('csrf_header')) +{ + /** + * Returns the CSRF header name. + * Can be used in Views by adding it to the meta tag + * or used in javascript to define a header name when using APIs. + * + * @return string + */ + function csrf_header(): string + { + $config = config(App::class); + + return $config->CSRFHeaderName; + } +} + +//-------------------------------------------------------------------- + if (! function_exists('csrf_hash')) { /** @@ -759,6 +778,23 @@ if (! function_exists('csrf_field')) //-------------------------------------------------------------------- +if (! function_exists('csrf_meta')) +{ + /** + * Generates a meta tag for use within javascript calls. + * + * @param string|null $id + * + * @return string + */ + function csrf_meta(string $id = null): string + { + return ''; + } +} + +//-------------------------------------------------------------------- + if (! function_exists('force_https')) { /** diff --git a/tests/system/CommonFunctionsTest.php b/tests/system/CommonFunctionsTest.php index 85282a6c69..5913c9946e 100644 --- a/tests/system/CommonFunctionsTest.php +++ b/tests/system/CommonFunctionsTest.php @@ -251,6 +251,11 @@ class CommonFunctionsTest extends \CIUnitTestCase $this->assertEquals('csrf_test_name', csrf_token()); } + public function testCSRFHeader() + { + $this->assertEquals('X-CSRF-TOKEN', csrf_header()); + } + public function testHash() { $this->assertEquals(32, strlen(csrf_hash())); @@ -261,6 +266,11 @@ class CommonFunctionsTest extends \CIUnitTestCase $this->assertContains('assertContains(' +.. php:function:: csrf_meta () + + :returns: A string with the HTML for meta tag with all required CSRF information. + :rtype: string + + Returns a meta tag with the CSRF information already inserted: + + + .. php:function:: force_https ( $duration = 31536000 [, $request = null [, $response = null]] ) :param int $duration: The number of seconds browsers should convert links to this resource to HTTPS.