jilo-web/app/includes/csrf_middleware.php

42 lines
1.2 KiB
PHP
Raw Normal View History

<?php
2025-02-17 14:50:57 +00:00
require_once __DIR__ . '/../helpers/security.php';
2025-02-19 13:31:01 +00:00
function applyCsrfMiddleware() {
$security = SecurityHelper::getInstance();
// Skip CSRF check for GET requests
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
return true;
}
2025-02-23 15:48:02 +00:00
// Skip CSRF check for initial login and registration attempts
if ($_SERVER['REQUEST_METHOD'] === 'POST' &&
2025-02-23 15:48:02 +00:00
isset($_GET['page']) &&
in_array($_GET['page'], ['login', 'register']) &&
!isset($_SESSION['username'])) {
return true;
}
// Check CSRF token for all other POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token = $_POST['csrf_token'] ?? '';
if (!$security->verifyCsrfToken($token)) {
// Log CSRF attempt
2025-02-23 11:51:36 +00:00
$logMessage = sprintf(
"CSRF attempt detected - IP: %s, Page: %s, User: %s",
$_SERVER['REMOTE_ADDR'],
$_GET['page'] ?? 'unknown',
$_SESSION['username'] ?? 'anonymous'
);
2025-02-23 15:48:02 +00:00
$logObject->insertLog(0, $logMessage, 'system');
// Return error message
http_response_code(403);
die('Invalid CSRF token. Please try again.');
}
}
return true;
}