1
0
mirror of https://github.com/flextype/flextype.git synced 2025-08-07 21:56:33 +02:00

feat(csrf): add Atomastic CSRF protection.

This commit is contained in:
Awilum
2021-02-09 22:13:47 +03:00
parent 75af8ab9af
commit 9a1ee30aab
3 changed files with 48 additions and 0 deletions

View File

@@ -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",

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* Flextype (https://flextype.org)
* Founded by Sergey Romanenko and maintained by Flextype Community.
*/
namespace Flextype\Middlewares;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class CsrfMiddleware
{
/**
* __invoke
*
* @param Request $request PSR7 request
* @param Response $response PSR7 response
* @param callable $next Next middleware
*/
public function __invoke(Request $request, Response $response, callable $next) : Response
{
$post_data = $request->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;
}
}

View File

@@ -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
*/