feat: Implement secure authentication module and integrate session management across multiple files

This commit is contained in:
2026-09-07 13:30:55 +02:00
parent 6d6833a417
commit 530e249b8f
6 changed files with 404 additions and 6 deletions
+90
View File
@@ -0,0 +1,90 @@
<?php
/**
* Web & PC Studio - Authenticatie & Beveiligingsmodule
* Veilig sessiebeheer, CSRF-protectie en one-way cryptografische verificatie.
*/
// Veilige sessie instellingen
if (session_status() === PHP_SESSION_NONE) {
ini_set('session.cookie_httponly', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_samesite', 'Strict');
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
ini_set('session.cookie_secure', '1');
}
session_start();
}
// One-way cryptografische hashes (Nooit plaintext opgeslagen)
define('AUTH_USER_HASH', 'ef8d40929f6f50e1f52009fbe94cf5a81b8373b90ed2bd130e85dcb4169c5cb4');
define('AUTH_PASS_HASH', '$2y$12$RQFrfxgd5ZiHQAcMX2DDluDW072QG/aDTDE50ORz3drcNnbZzl0AK');
/**
* Controleert of de huidige bezoeker geauthenticeerd is.
*/
function is_logged_in() {
if (!empty($_SESSION['wpc_auth']) && $_SESSION['wpc_auth'] === true) {
// Sessie timeout na 2 uur inactiviteit
if (isset($_SESSION['wpc_last_activity']) && (time() - $_SESSION['wpc_last_activity'] > 7200)) {
logout();
return false;
}
$_SESSION['wpc_last_activity'] = time();
return true;
}
return false;
}
/**
* Blokkeert ongeautoriseerde toegang en stuurt door naar het inlogscherm.
*/
function require_auth() {
if (!is_logged_in()) {
// Als het een asynchrone AJAX aanroep is, geef HTTP 401 Unauthorized
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) || isset($_GET['action']) || isset($_GET['api'])) {
header('HTTP/1.1 401 Unauthorized');
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'unauthorized', 'message' => 'Sessie verlopen of niet ingelogd.']);
exit;
}
$redirect = urlencode($_SERVER['REQUEST_URI'] ?? 'index.php');
header("Location: login.php?redirect={$redirect}");
exit;
}
}
/**
* Genereert een CSRF token voor formulieren.
*/
function get_csrf_token() {
if (empty($_SESSION['wpc_csrf'])) {
$_SESSION['wpc_csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['wpc_csrf'];
}
/**
* Valideert het ingediende CSRF token.
*/
function verify_csrf_token($token) {
if (empty($_SESSION['wpc_csrf']) || empty($token)) {
return false;
}
return hash_equals($_SESSION['wpc_csrf'], $token);
}
/**
* Beëindigt de sessie en ruimt cookies op.
*/
function logout() {
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
@session_destroy();
}