Implements the new session class

main
Yasen Pramatarov 2025-04-13 19:34:13 +03:00
parent dbdbe1bf49
commit f77e15bf44
3 changed files with 45 additions and 69 deletions

View File

@ -17,7 +17,7 @@ class Session {
* Start or resume a session with secure options * Start or resume a session with secure options
*/ */
public static function startSession() { public static function startSession() {
session_name('totalmeet'); session_name('jilo');
if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) { if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
session_start(self::$sessionOptions); session_start(self::$sessionOptions);
} }

View File

@ -33,21 +33,23 @@ try {
if ($action === 'verify' && isset($_SESSION['2fa_pending_user_id'])) { if ($action === 'verify' && isset($_SESSION['2fa_pending_user_id'])) {
// Handle 2FA verification // Handle 2FA verification
$code = $_POST['code'] ?? ''; $code = $_POST['code'] ?? '';
$userId = $_SESSION['2fa_pending_user_id']; $pending2FA = Session::get2FAPending();
$username = $_SESSION['2fa_pending_username'];
$rememberMe = isset($_SESSION['2fa_pending_remember']); if (!$pending2FA) {
header('Location: ' . htmlspecialchars($app_root) . '?page=login');
exit();
}
require_once '../app/classes/twoFactorAuth.php'; require_once '../app/classes/twoFactorAuth.php';
$twoFactorAuth = new TwoFactorAuthentication($db); $twoFactorAuth = new TwoFactorAuthentication($db);
if ($twoFactorAuth->verify($userId, $code)) { if ($twoFactorAuth->verify($pending2FA['user_id'], $code)) {
// Complete login // Complete login
handleSuccessfulLogin($userId, $username, $rememberMe, $config, $logObject, $user_IP); handleSuccessfulLogin($pending2FA['user_id'], $pending2FA['username'],
$pending2FA['remember_me'], $config, $logObject, $user_IP);
// Clean up 2FA session data // Clean up 2FA session data
unset($_SESSION['2fa_pending_user_id']); Session::clear2FAPending();
unset($_SESSION['2fa_pending_username']);
unset($_SESSION['2fa_pending_remember']);
exit(); exit();
} }
@ -232,11 +234,8 @@ try {
switch ($loginResult['status']) { switch ($loginResult['status']) {
case 'requires_2fa': case 'requires_2fa':
// Store pending 2FA info // Store pending 2FA info
$_SESSION['2fa_pending_user_id'] = $loginResult['user_id']; Session::store2FAPending($loginResult['user_id'], $loginResult['username'],
$_SESSION['2fa_pending_username'] = $loginResult['username']; isset($formData['remember_me']));
if (isset($formData['remember_me'])) {
$_SESSION['2fa_pending_remember'] = true;
}
// Redirect to 2FA verification // Redirect to 2FA verification
header('Location: ?page=login&action=verify'); header('Location: ?page=login&action=verify');
@ -282,36 +281,8 @@ include '../app/templates/form-login.php';
* Handle successful login by setting up session and cookies * Handle successful login by setting up session and cookies
*/ */
function handleSuccessfulLogin($userId, $username, $rememberMe, $config, $logObject, $userIP) { function handleSuccessfulLogin($userId, $username, $rememberMe, $config, $logObject, $userIP) {
if ($rememberMe) { // Create authenticated session
// 30*24*60*60 = 30 days Session::createAuthSession($userId, $username, $rememberMe, $config);
$cookie_lifetime = 30 * 24 * 60 * 60;
$setcookie_lifetime = time() + 30 * 24 * 60 * 60;
} else {
// 0 - session end on browser close
$cookie_lifetime = 0;
$setcookie_lifetime = 0;
}
// Regenerate session ID to prevent session fixation
session_regenerate_id(true);
// set session lifetime and cookies
setcookie('username', $username, [
'expires' => $setcookie_lifetime,
'path' => $config['folder'],
'domain' => $config['domain'],
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Strict'
]);
// Set session variables
$_SESSION['user_id'] = $userId;
$_SESSION['USERNAME'] = $username;
$_SESSION['LAST_ACTIVITY'] = time();
if ($rememberMe) {
$_SESSION['REMEMBER_ME'] = true;
}
// Log successful login // Log successful login
$logObject->insertLog($userId, "Login: User \"$username\" logged in. IP: $userIP", 'user'); $logObject->insertLog($userId, "Login: User \"$username\" logged in. IP: $userIP", 'user');

View File

@ -15,14 +15,18 @@
// flush it later only when there is no redirect // flush it later only when there is no redirect
ob_start(); ob_start();
// Start session before any session-dependent code
require_once '../app/classes/session.php';
Session::startSession();
// Apply security headers // Apply security headers
require_once '../app/includes/security_headers_middleware.php'; require_once '../app/includes/security_headers_middleware.php';
// sanitize all input vars that may end up in URLs or forms // sanitize all input vars that may end up in URLs or forms
require '../app/includes/sanitize.php'; require '../app/includes/sanitize.php';
session_name('jilo'); // Check session validity
session_start(); $validSession = Session::isValidSession();
// Initialize feedback message system // Initialize feedback message system
require_once '../app/classes/feedback.php'; require_once '../app/classes/feedback.php';
@ -64,6 +68,8 @@ $allowed_urls = [
'login', 'login',
'logout', 'logout',
'register', 'register',
'about',
]; ];
// cnfig file // cnfig file
@ -92,17 +98,26 @@ if ($config_file) {
$app_root = $config['folder']; $app_root = $config['folder'];
// check if logged in // List of pages that don't require authentication
unset($currentUser); $public_pages = ['login', 'register', 'help', 'about'];
if (isset($_COOKIE['username'])) {
if ( !isset($_SESSION['username']) ) { // Check if the requested page requires authentication
$_SESSION['username'] = $_COOKIE['username']; if (!isset($_COOKIE['username']) && !$validSession && !in_array($page, $public_pages)) {
} require_once '../app/includes/session_middleware.php';
$currentUser = htmlspecialchars($_SESSION['username']); applySessionMiddleware($config, $app_root);
} }
// redirect to login // Check session and redirect if needed
if ( !isset($_COOKIE['username']) && ($page !== 'login' && $page !== 'register') ) { $currentUser = null;
if ($validSession) {
$currentUser = Session::getUsername();
} else if (isset($_COOKIE['username']) && !in_array($page, $public_pages)) {
// Cookie exists but session is invalid - redirect to login
Feedback::flash('LOGIN', 'SESSION_TIMEOUT');
header('Location: ' . htmlspecialchars($app_root) . '?page=login&timeout=1');
exit();
} else if (!in_array($page, $public_pages)) {
// No valid session or cookie, and not a public page
header('Location: ' . htmlspecialchars($app_root) . '?page=login'); header('Location: ' . htmlspecialchars($app_root) . '?page=login');
exit(); exit();
} }
@ -164,11 +179,10 @@ if ($page == 'logout') {
$user_id = $userObject->getUserId($currentUser)[0]['id']; $user_id = $userObject->getUserId($currentUser)[0]['id'];
// clean up session // clean up session
session_unset(); Session::destroySession();
session_destroy();
// start new session for the login page // start new session for the login page
session_start(); Session::startSession();
setcookie('username', "", time() - 100, $config['folder'], $config['domain'], isset($_SERVER['HTTPS']), true); setcookie('username', "", time() - 100, $config['folder'], $config['domain'], isset($_SERVER['HTTPS']), true);
@ -186,8 +200,7 @@ if ($page == 'logout') {
} else { } else {
// if user is logged in, we need user details and rights // if user is logged in, we need user details and rights
if (isset($currentUser)) { if ($validSession) {
// If by error a logged in user requests the login page // If by error a logged in user requests the login page
if ($page === 'login') { if ($page === 'login') {
header('Location: ' . htmlspecialchars($app_root)); header('Location: ' . htmlspecialchars($app_root));
@ -211,18 +224,10 @@ if ($page == 'logout') {
} }
} }
// List of pages that don't require authentication
$public_pages = ['login', 'register'];
// Check if the requested page requires authentication
if (!in_array($page, $public_pages)) {
require_once '../app/includes/session_middleware.php';
}
// page building // page building
include '../app/templates/page-header.php'; include '../app/templates/page-header.php';
include '../app/templates/page-menu.php'; include '../app/templates/page-menu.php';
if (isset($currentUser)) { if ($validSession) {
include '../app/templates/page-sidebar.php'; include '../app/templates/page-sidebar.php';
} }
if (in_array($page, $allowed_urls)) { if (in_array($page, $allowed_urls)) {