Asked for: share a build with a link or build code, and an import tool that takes such a code. - "Teilen" on an own set creates a link (gear.php?build=CODE) and the same code as build code: 10 characters without 0/O and 1/I/L, shown as K7QX2-M9FRT, stored in gear_sets.share_code (schema version 59, unique; also in sql/schema.sql). Whoever opens it sees the set even if it is not on the profile, always in its current state; the session remembers the code so tabs, slots and compare work, and a renewed or withdrawn code ends that access. "Neuen Code erzeugen" and "Nicht mehr teilen" invalidate the old one. The dialog reopens after creating (#teilen) with copy buttons. - "Build importieren" on "Meine Sets" takes the code (with or without dash, any case) or the whole link; viewing someone else's set (shared or on the profile) offers "In meine Sets übernehmen". Both copy the set with gear, skills, macros and all planner pages via gear_set_copy() (also used by "Kopieren" now); the copy is neither shared nor on the profile. Errors reopen the dialog (#import). - Members only (gear.view). Opening any page without being logged in now brings you back to it after the login (auth_login_return_target) - only for page views in the browser, not for background requests like live updates or autosave. - Privacy policy (shared sets), patch notes and README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
304 lines
12 KiB
PHP
304 lines
12 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/discord_auth.php';
|
|
|
|
function current_user(): ?array
|
|
{
|
|
static $user = null;
|
|
static $loaded = false;
|
|
|
|
if ($loaded) {
|
|
return $user;
|
|
}
|
|
$loaded = true;
|
|
|
|
if (empty($_SESSION['user_id'])) {
|
|
return null;
|
|
}
|
|
|
|
$stmt = db()->prepare(
|
|
'SELECT id, username, display_name, class_name, classes, main_class, status, must_change_password, password_login, discord_id, discord_username,
|
|
avatar_filename, avatar_sync, tour_completed_at, is_admin, session_epoch
|
|
FROM users WHERE id = ?'
|
|
);
|
|
$stmt->execute([$_SESSION['user_id']]);
|
|
$row = $stmt->fetch();
|
|
|
|
// Gesperrte oder geloeschte Konten verlieren die Sitzung. "pending" bleibt angemeldet,
|
|
// sieht aber nur die Seite "Freischaltung ausstehend" (siehe require_login()).
|
|
if (!$row || !in_array($row['status'], ['active', 'pending'], true)) {
|
|
session_destroy();
|
|
return null;
|
|
}
|
|
|
|
// Sitzungen beendet (gesperrt, "Abmelden erzwingen" oder Notbremse): Zaehler passt nicht mehr.
|
|
if ((int) ($_SESSION['session_epoch'] ?? 0) !== (int) $row['session_epoch']) {
|
|
auth_force_logout('Du wurdest abgemeldet. Bitte melde dich erneut an.');
|
|
return null;
|
|
}
|
|
|
|
// Mitgliedschaft und Rollen live mit Discord abgleichen (hoechstens alle paar Minuten).
|
|
$check = discord_live_check((int) $row['id']);
|
|
$viaDiscord = ($_SESSION['login_method'] ?? '') === 'discord';
|
|
|
|
if ($check === 'left' && ($viaDiscord || empty($row['password_login']))) {
|
|
auth_force_logout('Du bist nicht mehr auf dem Discord-Server der Legion und wurdest abgemeldet.');
|
|
return null;
|
|
}
|
|
if ($check === 'revoked' && $viaDiscord) {
|
|
auth_force_logout('Deine Discord-Anmeldung ist abgelaufen - bitte melde dich erneut an.');
|
|
return null;
|
|
}
|
|
|
|
// "Zuletzt aktiv" fuer die Mitgliederliste - nicht bei jedem Seitenaufruf schreiben.
|
|
if (($_SESSION['last_seen_touch'] ?? 0) < time() - 300) {
|
|
$_SESSION['last_seen_touch'] = time();
|
|
try {
|
|
db()->prepare('UPDATE users SET last_seen_at = ? WHERE id = ?')->execute([date('Y-m-d H:i:s'), (int) $row['id']]);
|
|
} catch (PDOException $e) {
|
|
// Spalte kommt erst mit dem naechsten Schema-Abgleich
|
|
}
|
|
}
|
|
|
|
$user = $row;
|
|
return $user;
|
|
}
|
|
|
|
/** 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);
|
|
}
|
|
|
|
/**
|
|
* Wohin nach dem Login: zur Seite, die vorher ohne Anmeldung aufgerufen wurde (require_login), sonst ins Dashboard.
|
|
* Nur Pfade dieser Website - keine fremden Adressen.
|
|
*/
|
|
function auth_login_return_target(): string
|
|
{
|
|
$target = (string) ($_SESSION['login_return'] ?? '');
|
|
unset($_SESSION['login_return']);
|
|
return preg_match('~^/(?![/\\\\])~', $target) && !preg_match('/[\x00-\x1f]/', $target) ? $target : '/dashboard.php';
|
|
}
|
|
|
|
/** Meldet einen Nutzer an (nach Passwort- oder Discord-Login). */
|
|
function auth_login_session(int $userId, string $method): void
|
|
{
|
|
session_regenerate_id(true);
|
|
$_SESSION['user_id'] = $userId;
|
|
$_SESSION['login_method'] = $method;
|
|
$epoch = db()->prepare('SELECT session_epoch FROM users WHERE id = ?');
|
|
$epoch->execute([$userId]);
|
|
$_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']);
|
|
// Beantragte Kontoloeschung: Anmelden vor Ablauf der Frist bricht sie ab (includes/account_deletion.php)
|
|
account_deletion_on_login($userId);
|
|
}
|
|
|
|
function require_login(): void
|
|
{
|
|
$user = current_user();
|
|
if (!$user) {
|
|
// Aufgerufene Seite fuer nach dem Login merken (z.B. ein geteilter Build-Link aus Discord) - nur beim Aufruf im
|
|
// Browser, nicht bei Abrufen im Hintergrund (Live-Aktualisierung, Autosave), die sonst dort landen wuerden
|
|
$mode = (string) ($_SERVER['HTTP_SEC_FETCH_MODE'] ?? '');
|
|
$isPageView = ($_SERVER['REQUEST_METHOD'] ?? '') === 'GET' && empty($_SERVER['HTTP_X_REQUESTED_WITH'])
|
|
&& ($mode !== '' ? $mode === 'navigate' : str_contains((string) ($_SERVER['HTTP_ACCEPT'] ?? ''), 'text/html'));
|
|
if ($isPageView) {
|
|
$_SESSION['login_return'] = (string) ($_SERVER['REQUEST_URI'] ?? '');
|
|
}
|
|
redirect('/login.php');
|
|
}
|
|
|
|
$currentScript = basename((string) ($_SERVER['SCRIPT_NAME'] ?? ''));
|
|
|
|
if ($user['status'] === 'pending') {
|
|
if (!in_array($currentScript, ['pending.php', 'logout.php'], true)) {
|
|
redirect('/pending.php');
|
|
}
|
|
return;
|
|
}
|
|
|
|
$exemptScripts = ['change_password.php', 'logout.php'];
|
|
if (!empty($user['must_change_password']) && !empty($user['password_login'])
|
|
&& !in_array($currentScript, $exemptScripts, true)) {
|
|
redirect('/change_password.php');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Anmeldung mit Benutzername und Passwort.
|
|
*
|
|
* @return string Leer bei Erfolg, sonst die Fehlermeldung fuer die Login-Seite.
|
|
*/
|
|
function attempt_login(string $username, string $password): string
|
|
{
|
|
// Bremse nach Fehlversuchen - pro IP, nicht pro Konto (siehe includes/security.php)
|
|
$blocked = login_throttle_check($username);
|
|
if ($blocked !== '') {
|
|
return $blocked;
|
|
}
|
|
|
|
$stmt = db()->prepare('SELECT id, password_hash, status, password_login FROM users WHERE username = ?');
|
|
$stmt->execute([$username]);
|
|
$row = $stmt->fetch();
|
|
|
|
if (!$row || !password_verify($password, $row['password_hash'])) {
|
|
login_throttle_fail($username);
|
|
return 'Login fehlgeschlagen. Bitte Zugangsdaten prüfen.';
|
|
}
|
|
if ($row['status'] === 'disabled') {
|
|
return 'Dieses Konto ist gesperrt.';
|
|
}
|
|
// Erst nach dem Passwort pruefen - sonst liesse sich ohne Passwort herausfinden,
|
|
// welche Benutzernamen es gibt.
|
|
if (empty($row['password_login'])) {
|
|
return 'Für dieses Konto ist die Anmeldung mit Passwort nicht freigeschaltet. Bitte melde dich über Discord an.';
|
|
}
|
|
|
|
auth_login_session((int) $row['id'], 'password');
|
|
return '';
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|