From 9a1ee30aab782292ae6871091ddade1886f0adb0 Mon Sep 17 00:00:00 2001 From: Awilum Date: Tue, 9 Feb 2021 22:13:47 +0300 Subject: [PATCH] feat(csrf): add Atomastic CSRF protection. --- composer.json | 1 + src/flextype/Middlewares/CsrfMiddleware.php | 40 +++++++++++++++++++++ src/flextype/bootstrap.php | 7 ++++ 3 files changed, 48 insertions(+) create mode 100644 src/flextype/Middlewares/CsrfMiddleware.php diff --git a/composer.json b/composer.json index ec99f4df..eabf1ec0 100755 --- a/composer.json +++ b/composer.json @@ -32,6 +32,7 @@ "atomastic/registry": "^2.0.0", "atomastic/strings": "^2.4.0", "atomastic/macroable": "^1.0.0", + "atomastic/csrf": "^1.0.1", "slim/slim": "^3.12.3", diff --git a/src/flextype/Middlewares/CsrfMiddleware.php b/src/flextype/Middlewares/CsrfMiddleware.php new file mode 100644 index 00000000..ec4715b1 --- /dev/null +++ b/src/flextype/Middlewares/CsrfMiddleware.php @@ -0,0 +1,40 @@ +getParsedBody(); + + if (isset($post_data[flextype('csrf')->getTokenName()])) { + if (flextype('csrf')->isValid($post_data[flextype('csrf')->getTokenName()])) { + $response = $next($request, $response); + } else { + $response = $response->write('This looks like a cross-site request forgery!'); + } + } else { + $response = $next($request, $response); + } + + return $response; + } +} diff --git a/src/flextype/bootstrap.php b/src/flextype/bootstrap.php index c39e2fa7..bee23617 100755 --- a/src/flextype/bootstrap.php +++ b/src/flextype/bootstrap.php @@ -9,6 +9,8 @@ declare(strict_types=1); namespace Flextype; +use Atomastic\Csrf\Csrf; +use Atomastic\Session\Session; use Atomastic\Registry\Registry; use Flextype\Foundation\Flextype; use Slim\Http\Environment; @@ -117,6 +119,11 @@ flextype('session')->setOptions(flextype('registry')->get('flextype.settings.ses */ flextype('session')->start(); +/** + * Add CSRF (cross-site request forgery) protection service to Flextype container + */ +flextype()->container()['csrf'] = fn() => new Csrf('__csrf_token', '', 128); + /** * Set internal encoding */