feat: Add CSRF protection

This commit is contained in:
overflowerror 2024-08-01 21:36:58 +02:00
parent b4cedafa27
commit 3c2bb65bfe
3 changed files with 19 additions and 1 deletions

View file

@ -3,12 +3,14 @@
require_once __DIR__ . "/../core.php";
require_once __DIR__ . "/../lib/pairing.php";
require_once __DIR__ . "/../lib/rating.php";
require_once __DIR__ . "/../lib/security.php";
function renderChoice(): void {
[$left, $right] = [$_SESSION["left"], $_SESSION["right"]];
$csrfToken = $_SESSION["csrfToken"];
$title = "Test";
$content = function() use ($left, $right) {
$content = function() use ($left, $right, $csrfToken) {
include __DIR__ . "/../view/fragments/mobSelection.php";
};
@ -28,6 +30,10 @@ const LEFT = 0;
const RIGHT = 1;
function voteAndNextPairing(int $winner): array {
if ($_POST["csrfToken"] != $_SESSION["csrfToken"]) {
return [$_SESSION["left"], $_SESSION["right"]];
}
addMatch($_SESSION["left"]["id"], $_SESSION["right"]["id"], $winner, session_id());
$winnerMob = ($winner == 0) ? $_SESSION["left"] : $_SESSION["right"];
@ -54,5 +60,6 @@ session_start();
if ($render) {
renderChoice();
} else {
$_SESSION["csrfToken"] = makeCcrfToken();
reload();
}

5
lib/security.php Normal file
View file

@ -0,0 +1,5 @@
<?php
function makeCcrfToken(): string {
return bin2hex(random_bytes(8));
}

View file

@ -1,4 +1,10 @@
<?php
$side ??= "";
$mob ??= [];
$csrfToken ??= "";
?>
<form action="?<?= $side ?>" method="POST" name="<?= $side ?>" id="form-<?= $side ?>">
<input type="hidden" name="csrfToken" value="<?= $csrfToken ?>">
<div class="mob" onclick="document.forms['<?= $side ?>'].submit()">
<h2><?= $mob["name"]; ?></h2>
<img alt="<?= $mob["name"]; ?>" src="/images/mobs/<?= $mob["image"] ?? "_placeholder.png"; ?>">