encrypt and decrypt persistent tokens

This commit is contained in:
Ryan
2025-03-23 23:29:51 -04:00
committed by GitHub
parent 0215bd3d76
commit 5892236aa9
4 changed files with 109 additions and 37 deletions

View File

@@ -1,17 +1,36 @@
<?php
session_start();
require 'config.php';
// Retrieve headers and check CSRF token.
$headers = array_change_key_case(getallheaders(), CASE_LOWER);
$receivedToken = isset($headers['x-csrf-token']) ? trim($headers['x-csrf-token']) : '';
// Fallback: If a CSRF token exists in the session and doesn't match the one provided,
// log the mismatch but proceed with logout.
// If there's a mismatch, log it but continue with logout.
if (isset($_SESSION['csrf_token']) && $receivedToken !== $_SESSION['csrf_token']) {
// Optionally log this event:
error_log("CSRF token mismatch on logout. Proceeding with logout.");
}
$_SESSION = []; // Clear session data
session_destroy(); // Destroy session
// If the remember me token is set, remove it from the persistent tokens file.
if (isset($_COOKIE['remember_me_token'])) {
$token = $_COOKIE['remember_me_token'];
$persistentTokensFile = USERS_DIR . 'persistent_tokens.json';
if (file_exists($persistentTokensFile)) {
$encryptedContent = file_get_contents($persistentTokensFile);
$decryptedContent = decryptData($encryptedContent, $encryptionKey);
$persistentTokens = json_decode($decryptedContent, true);
if (is_array($persistentTokens) && isset($persistentTokens[$token])) {
unset($persistentTokens[$token]);
$newEncryptedContent = encryptData(json_encode($persistentTokens, JSON_PRETTY_PRINT), $encryptionKey);
file_put_contents($persistentTokensFile, $newEncryptedContent, LOCK_EX);
}
}
// Clear the cookie.
setcookie('remember_me_token', '', time() - 3600, '/', '', $secure, true);
}
// Clear session data and destroy the session.
$_SESSION = [];
session_destroy();
header('Content-Type: application/json');
echo json_encode(["success" => "Logged out"]);