Skip to content

Commit

Permalink
feature: send csrf tokens in the header
Browse files Browse the repository at this point in the history
closes #572
  • Loading branch information
g105b committed Sep 24, 2022
1 parent 72a4c8d commit a5bb470
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 54 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"php": ">=8.1",

"phpgt/config": "^1.0",
"phpgt/csrf": "^v1.9",
"phpgt/dom": "^v4.0",
"phpgt/domtemplate": "^v3.1",
"phpgt/database": "^1.4",
Expand Down
142 changes: 100 additions & 42 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 14 additions & 12 deletions src/Middleware/RequestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
use Gt\Config\Config;
use Gt\Config\ConfigFactory;
use Gt\Config\ConfigSection;
use Gt\Csrf\HTMLDocumentProtector;
use Gt\Csrf\SessionTokenStore;
use Gt\Dom\HTMLDocument;
use Gt\DomTemplate\ComponentExpander;
use Gt\DomTemplate\DocumentBinder;
Expand Down Expand Up @@ -183,7 +185,6 @@ public function handle(
$viewModel->body->classList->add($bodyDirClass);
}

// ini_set('session.serialize_handler', 'php_serialize');
$sessionConfig = $this->config->getSection("session");
$sessionId = $_COOKIE[$sessionConfig["name"]] ?? null;
$sessionHandler = SessionSetup::attachHandler(
Expand All @@ -196,17 +197,18 @@ public function handle(
);
$serviceContainer->set($session);

// TODO: Complete CSRF implementation - maybe use its own cookie?
// /** @var Session $session */
// $session = $serviceContainer->get(Session::class);
// $csrfTokenStore = new SessionTokenStore($session->getStore("csrf", true));
//
// if($request->getMethod() === "POST") {
// $csrfTokenStore->processAndVerify($_POST);
// }
//
// $protector = new HTMLDocumentProtector($viewModel, $csrfTokenStore);
// $protector->protectAndInject();
$session = $serviceContainer->get(Session::class);
$csrfTokenStore = new SessionTokenStore(
$session->getStore("csrf", true)
);

if($request->getMethod() === "POST") {
$csrfTokenStore->verify($_POST);
}

$protector = new HTMLDocumentProtector($viewModel, $csrfTokenStore);
$tokens = $protector->protect(HTMLDocumentProtector::ONE_TOKEN_PER_FORM);
$response = $response->withHeader("x-csrf", $tokens);
}

// TODO: Kill globals.
Expand Down

0 comments on commit a5bb470

Please sign in to comment.