From e2f1fc53fd8df95d32f3ae71b32174768d11e2bd Mon Sep 17 00:00:00 2001 From: Maaxxs <61059039+MaaxxsDev@users.noreply.github.com> Date: Tue, 22 Sep 2026 08:36:53 +0200 Subject: [PATCH] Stay logged in for 30 days: remember-me cookie restores the login when the PHP session is gone Co-Authored-By: Claude Opus 5 --- admin/user_form.php | 1 + change_password.php | 2 + includes/auth.php | 133 +++++++++++++++++++++++++++++++++++++++++ includes/bootstrap.php | 3 + includes/schema.php | 23 ++++++- sql/schema.sql | 20 +++++++ 6 files changed, 181 insertions(+), 1 deletion(-) diff --git a/admin/user_form.php b/admin/user_form.php index fa57b25..3d2c18a 100644 --- a/admin/user_form.php +++ b/admin/user_form.php @@ -121,6 +121,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($password !== '') { $stmt = $pdo->prepare('UPDATE users SET username=?, display_name=?, status=?, password_hash=?, must_change_password=?, password_login=?, is_admin=? WHERE id=?'); $stmt->execute([$username, $displayName, $status, password_hash($password, PASSWORD_DEFAULT), $forceChange, $passwordLogin, $isAdmin, $editId]); + auth_remember_revoke($editId); } else { $stmt = $pdo->prepare('UPDATE users SET username=?, display_name=?, status=?, must_change_password=?, password_login=?, is_admin=? WHERE id=?'); $stmt->execute([$username, $displayName, $status, $forceChange, $passwordLogin, $isAdmin, $editId]); diff --git a/change_password.php b/change_password.php index 44e980e..0f0f8e7 100644 --- a/change_password.php +++ b/change_password.php @@ -18,6 +18,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { } else { $stmt = db()->prepare('UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?'); $stmt->execute([password_hash($newPassword, PASSWORD_DEFAULT), $user['id']]); + // Andere Geraete bleiben nicht mehr angemeldet, dieser Browser schon + auth_remember_revoke((int) $user['id'], true); set_flash('success', 'Passwort wurde geƤndert.'); redirect('/dashboard.php'); } diff --git a/includes/auth.php b/includes/auth.php index 540861e..7b43f67 100644 --- a/includes/auth.php +++ b/includes/auth.php @@ -68,6 +68,7 @@ function current_user(): ?array /** Beendet die Anmeldung, behaelt aber die Sitzung fuer eine Meldung auf der Login-Seite. */ function auth_force_logout(string $message): void { + auth_remember_forget(); $_SESSION = []; session_regenerate_id(true); set_flash('error', $message); @@ -84,6 +85,7 @@ function auth_login_session(int $userId, string $method): void $_SESSION['session_epoch'] = (int) $epoch->fetchColumn(); db()->prepare('UPDATE users SET last_login = NOW() WHERE id = ?')->execute([$userId]); + auth_remember_issue($userId, $method, (int) $_SESSION['session_epoch']); } function require_login(): void @@ -145,6 +147,137 @@ function attempt_login(string $username, string $password): string function logout(): void { + auth_remember_forget(); $_SESSION = []; session_destroy(); } + +// ---- Angemeldet bleiben ---- +// Die PHP-Sitzung allein haelt nicht lange: Das Cookie verfaellt beim Schliessen des Browsers und +// der Hoster raeumt Sitzungen nach kurzer Zeit weg. Deshalb bekommt jede Anmeldung zusaetzlich ein +// Cookie "selector:validator"; in der Datenbank steht nur der Hash des validators. Ist die Sitzung +// weg, meldet auth_remember_restore() das Konto damit wieder an. Das Token verlaengert sich bei +// Benutzung - wer mindestens alle 30 Tage vorbeischaut, bleibt also angemeldet. +// "Abmelden erzwingen", Sperren und die Notbremse (users.session_epoch) machen es sofort ungueltig. + +const AUTH_REMEMBER_COOKIE = 'lumina_login'; +const AUTH_REMEMBER_DAYS = 30; + +function auth_remember_cookie(string $value, int $expires): void +{ + if (headers_sent()) { + return; + } + setcookie(AUTH_REMEMBER_COOKIE, $value, [ + 'expires' => $expires, + 'path' => '/', + 'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off', + 'httponly' => true, + 'samesite' => 'Lax', + ]); +} + +/** Legt nach einer Anmeldung ein neues Token an und setzt das Cookie. */ +function auth_remember_issue(int $userId, string $method, int $epoch): void +{ + $selector = bin2hex(random_bytes(12)); + $validator = bin2hex(random_bytes(32)); + $expires = time() + AUTH_REMEMBER_DAYS * 86400; + try { + $pdo = db(); + // Abgelaufene Tokens nebenbei aufraeumen + $pdo->exec('DELETE FROM auth_tokens WHERE expires_at < NOW()'); + $pdo->prepare( + 'INSERT INTO auth_tokens (user_id, selector, validator_hash, login_method, session_epoch, user_agent, last_used_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)' + )->execute([ + $userId, $selector, hash('sha256', $validator), $method === 'discord' ? 'discord' : 'password', $epoch, + mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255) ?: null, date('Y-m-d H:i:s', $expires), + ]); + } catch (PDOException $e) { + return; // Tabelle kommt erst mit dem naechsten Schema-Abgleich - dann eben nur die Sitzung + } + auth_remember_cookie($selector . ':' . $validator, $expires); +} + +/** Token des aktuellen Browsers loeschen (Abmelden) und das Cookie entfernen. */ +function auth_remember_forget(): void +{ + $cookie = (string) ($_COOKIE[AUTH_REMEMBER_COOKIE] ?? ''); + if ($cookie !== '') { + [$selector] = explode(':', $cookie, 2); + try { + db()->prepare('DELETE FROM auth_tokens WHERE selector = ?')->execute([$selector]); + } catch (PDOException $e) { + // egal - das Cookie wird trotzdem entfernt + } + unset($_COOKIE[AUTH_REMEMBER_COOKIE]); + auth_remember_cookie('', time() - 3600); + } +} + +/** + * Nach einer Passwortaenderung: "angemeldet bleiben" auf allen Geraeten beenden - auf Wunsch + * ausser dem aktuellen Browser (wenn das Mitglied sein eigenes Passwort aendert). + */ +function auth_remember_revoke(int $userId, bool $keepCurrent = false): void +{ + $current = $keepCurrent ? explode(':', (string) ($_COOKIE[AUTH_REMEMBER_COOKIE] ?? ''), 2)[0] : ''; + try { + db()->prepare('DELETE FROM auth_tokens WHERE user_id = ? AND selector <> ?')->execute([$userId, $current]); + } catch (PDOException $e) { + // Tabelle kommt erst mit dem naechsten Schema-Abgleich + } +} + +/** + * Keine Anmeldung in der Sitzung, aber ein gueltiges Cookie: Konto wieder anmelden. + * Laeuft in bootstrap.php, bevor irgendetwas ausgegeben wird (Cookie/Session-ID erneuern). + */ +function auth_remember_restore(): void +{ + if (!empty($_SESSION['user_id'])) { + return; + } + $cookie = (string) ($_COOKIE[AUTH_REMEMBER_COOKIE] ?? ''); + if (!preg_match('/^([a-f0-9]{24}):([a-f0-9]{64})$/', $cookie, $m)) { + if ($cookie !== '') { + auth_remember_cookie('', time() - 3600); + } + return; + } + try { + $stmt = db()->prepare( + 'SELECT t.id, t.user_id, t.validator_hash, t.login_method, t.session_epoch, t.expires_at, t.last_used_at, + u.status, u.session_epoch AS user_epoch + FROM auth_tokens t JOIN users u ON u.id = t.user_id WHERE t.selector = ?' + ); + $stmt->execute([$m[1]]); + $token = $stmt->fetch(); + } catch (PDOException $e) { + return; + } + + $valid = $token + && hash_equals((string) $token['validator_hash'], hash('sha256', $m[2])) + && strtotime((string) $token['expires_at']) > time() + && (int) $token['session_epoch'] === (int) $token['user_epoch'] + && in_array($token['status'], ['active', 'pending'], true); + if (!$valid) { + auth_remember_forget(); + return; + } + + session_regenerate_id(true); + $_SESSION['user_id'] = (int) $token['user_id']; + $_SESSION['login_method'] = (string) $token['login_method']; + $_SESSION['session_epoch'] = (int) $token['user_epoch']; + + // Laufzeit verlaengern (hoechstens einmal am Tag schreiben) + if (strtotime((string) ($token['last_used_at'] ?? '')) < time() - 86400) { + $expires = time() + AUTH_REMEMBER_DAYS * 86400; + db()->prepare('UPDATE auth_tokens SET last_used_at = NOW(), expires_at = ? WHERE id = ?') + ->execute([date('Y-m-d H:i:s', $expires), (int) $token['id']]); + auth_remember_cookie($cookie, $expires); + } +} diff --git a/includes/bootstrap.php b/includes/bootstrap.php index 49362ba..d88ffee 100644 --- a/includes/bootstrap.php +++ b/includes/bootstrap.php @@ -39,5 +39,8 @@ require_once __DIR__ . '/moderation.php'; ensure_schema(); +// Sitzung abgelaufen, aber "angemeldet bleiben"-Cookie da: wieder anmelden (includes/auth.php) +auth_remember_restore(); + // Tempolimit fuer abgeschickte Formulare (Spam-/Missbrauchsschutz, siehe includes/security.php) security_guard_post(); diff --git a/includes/schema.php b/includes/schema.php index 5c57c54..c4dfd75 100644 --- a/includes/schema.php +++ b/includes/schema.php @@ -11,7 +11,7 @@ declare(strict_types=1); */ // Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu. -const SCHEMA_VERSION = 23; +const SCHEMA_VERSION = 24; /** * Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql). @@ -19,6 +19,27 @@ const SCHEMA_VERSION = 23; function schema_table_upgrades(): array { return [ + // "Angemeldet bleiben" (includes/auth.php) + 'auth_tokens' => <<<'SQL' +CREATE TABLE IF NOT EXISTS auth_tokens ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + user_id INT UNSIGNED NOT NULL, + -- Cookie "selector:validator": selector zum Nachschlagen, vom validator nur der SHA-256-Hash + selector CHAR(24) NOT NULL UNIQUE, + validator_hash CHAR(64) NOT NULL, + -- password | discord (wie $_SESSION['login_method']) + login_method VARCHAR(10) NOT NULL DEFAULT 'password', + -- Stand von users.session_epoch beim Anmelden - passt er nicht mehr, ist das Token ungueltig + session_epoch INT UNSIGNED NOT NULL DEFAULT 0, + user_agent VARCHAR(255) NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_used_at DATETIME NULL, + expires_at DATETIME NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_auth_tokens_user (user_id), + INDEX idx_auth_tokens_expires (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +SQL, 'warehouse_items' => <<<'SQL' CREATE TABLE IF NOT EXISTS warehouse_items ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, diff --git a/sql/schema.sql b/sql/schema.sql index 9f701df..f72a05e 100644 --- a/sql/schema.sql +++ b/sql/schema.sql @@ -117,6 +117,26 @@ CREATE TABLE IF NOT EXISTS user_roles ( FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +-- "Angemeldet bleiben": langlebige Anmeldung per Cookie (includes/auth.php) +CREATE TABLE IF NOT EXISTS auth_tokens ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + user_id INT UNSIGNED NOT NULL, + -- Cookie "selector:validator": selector zum Nachschlagen, vom validator nur der SHA-256-Hash + selector CHAR(24) NOT NULL UNIQUE, + validator_hash CHAR(64) NOT NULL, + -- password | discord (wie $_SESSION['login_method']) + login_method VARCHAR(10) NOT NULL DEFAULT 'password', + -- Stand von users.session_epoch beim Anmelden - passt er nicht mehr, ist das Token ungueltig + session_epoch INT UNSIGNED NOT NULL DEFAULT 0, + user_agent VARCHAR(255) NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_used_at DATETIME NULL, + expires_at DATETIME NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_auth_tokens_user (user_id), + INDEX idx_auth_tokens_expires (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + -- -------------------------------------------------------------------------- -- Raids: Einstellungen und Anwesenheit (die Raids selbst liegen beim Bot) -- --------------------------------------------------------------------------