32768, 'time_cost' => 3, 'threads' => 1, ]); } return password_hash($password, PASSWORD_DEFAULT); } function password_needs_upgrade(string $hash): bool { if (defined('PASSWORD_ARGON2ID')) { return password_needs_rehash($hash, PASSWORD_ARGON2ID, [ 'memory_cost' => 32768, 'time_cost' => 3, 'threads' => 1, ]); } return password_needs_rehash($hash, PASSWORD_DEFAULT); } function auth_user(): ?array { static $loaded = false; static $user = null; if ($loaded) { return $user; } $loaded = true; $uid = $_SESSION['uid'] ?? null; if (!is_int($uid) && !ctype_digit((string) $uid)) { auth_restore_from_remember(); $uid = $_SESSION['uid'] ?? null; if (!is_int($uid) && !ctype_digit((string) $uid)) { return null; } } $stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1'); $stmt->execute([(int) $uid]); $row = $stmt->fetch(); if (!$row || $row['status'] !== 'active') { auth_clear_session(); return null; } if ((int) ($_SESSION['epoch'] ?? 0) !== (int) $row['auth_epoch']) { auth_clear_session(); return null; } $now = time(); $idleLimit = (int) config('app.session_idle_seconds', 2592000); $absoluteLimit = (int) config('app.session_absolute_seconds', 7776000); $created = (int) ($_SESSION['created'] ?? 0); $lastSeen = (int) ($_SESSION['last_seen'] ?? 0); if ($created === 0 || $lastSeen === 0 || $now - $lastSeen > $idleLimit || $now - $created > $absoluteLimit ) { auth_clear_session(); return null; } if ($now - $lastSeen > 300) { $_SESSION['last_seen'] = $now; } $row['id'] = (int) $row['id']; $row['auth_epoch'] = (int) $row['auth_epoch']; $row['must_change_password'] = (int) $row['must_change_password']; $user = $row; return $user; } function auth_user_by_id(int $id): ?array { $stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1'); $stmt->execute([$id]); $row = $stmt->fetch(); if (!$row) { return null; } $row['id'] = (int) $row['id']; $row['auth_epoch'] = (int) $row['auth_epoch']; $row['must_change_password'] = (int) $row['must_change_password']; return $row; } function auth_login(array $user, bool $remember = false): void { session_regenerate_id(true); $_SESSION['uid'] = (int) $user['id']; $_SESSION['epoch'] = (int) $user['auth_epoch']; $_SESSION['created'] = time(); $_SESSION['last_seen'] = time(); $_SESSION['csrf'] = bin2hex(random_bytes(32)); db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?') ->execute([utc_now(), (int) $user['id']]); db()->prepare('DELETE FROM login_attempts WHERE login_key = ?') ->execute([auth_login_key((string) $user['username'])]); if ($remember) { auth_issue_remember((int) $user['id']); } } function auth_clear_session(): void { $_SESSION = []; if (session_status() === PHP_SESSION_ACTIVE) { session_regenerate_id(true); } } function auth_logout(): void { auth_forget_remember(); auth_clear_session(); if (session_status() === PHP_SESSION_ACTIVE) { session_destroy(); } } function auth_require_login(): array { $user = auth_user(); if ($user === null) { $target = current_path(); $query = (string) ($_SERVER['QUERY_STRING'] ?? ''); if ($query !== '') { $target .= '?' . $query; } redirect('/login?next=' . rawurlencode($target)); } return $user; } function auth_require_admin(): array { $user = auth_require_login(); if (($user['role'] ?? '') !== 'admin') { abort_page(403, 'Diese Seite ist nur für den Spielleiter bestimmt.'); } return $user; } function auth_login_key(string $identifier): string { return mb_strtolower(trim($identifier), 'UTF-8'); } function auth_find_by_login(string $identifier): ?array { $needle = trim($identifier); if ($needle === '') { return null; } $stmt = db()->prepare( 'SELECT * FROM users WHERE username = ? OR (email IS NOT NULL AND email <> \'\' AND email = ?) LIMIT 1' ); $stmt->execute([$needle, $needle]); $row = $stmt->fetch(); return $row ?: null; } function auth_username_taken(string $username, int $ignoreId = 0): bool { $stmt = db()->prepare('SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1'); $stmt->execute([$username, $ignoreId]); return (bool) $stmt->fetchColumn(); } function auth_email_taken(string $email, int $ignoreId = 0): bool { if ($email === '') { return false; } $stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1'); $stmt->execute([$email, $ignoreId]); return (bool) $stmt->fetchColumn(); } function auth_is_locked_out(string $identifier): bool { $window = (int) config('app.login_window_seconds', 900); $maxIp = (int) config('app.login_max_per_ip', 15); $maxUser = (int) config('app.login_max_per_user', 5); $stmt = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND attempted_at >= ?'); $stmt->execute([client_ip(), utc_after(-$window)]); if ((int) $stmt->fetchColumn() >= $maxIp) { return true; } $stmt = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE login_key = ? AND attempted_at >= ?'); $stmt->execute([auth_login_key($identifier), utc_after(-$window)]); return (int) $stmt->fetchColumn() >= $maxUser; } function auth_record_failure(string $identifier): void { db()->prepare('INSERT INTO login_attempts (ip, login_key, attempted_at) VALUES (?, ?, ?)') ->execute([client_ip(), auth_login_key($identifier), utc_now()]); $window = (int) config('app.login_window_seconds', 900); db()->prepare('DELETE FROM login_attempts WHERE attempted_at < ?') ->execute([utc_after(-max($window * 8, 86400))]); } function auth_verify_login(string $identifier, string $password): array { if (auth_is_locked_out($identifier)) { throw new RuntimeException('locked'); } $user = auth_find_by_login($identifier); $hash = $user['password_hash'] ?? WS_DUMMY_HASH; $ok = password_verify($password, $hash); if (!$user || !$ok) { auth_record_failure($identifier); throw new RuntimeException('invalid'); } if ($user['status'] !== 'active') { auth_record_failure($identifier); throw new RuntimeException('disabled'); } if (password_needs_upgrade($hash)) { db()->prepare('UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?') ->execute([hash_password($password), utc_now(), (int) $user['id']]); } return $user; } function auth_invalidate_sessions(int $userId): void { db()->prepare('UPDATE users SET auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?') ->execute([utc_now(), $userId]); db()->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]); } function auth_can_manage(?array $user): bool { return is_array($user) && ($user['role'] ?? '') === 'admin'; } /* ------------------------------------------------------ Angemeldet bleiben */ function auth_issue_remember(int $userId): void { $selector = bin2hex(random_bytes(12)); $validator = bin2hex(random_bytes(32)); $lifetime = (int) config('app.remember_seconds', 7776000); db()->prepare('DELETE FROM auth_tokens WHERE expires_at < ?')->execute([utc_now()]); db()->prepare('INSERT INTO auth_tokens (user_id, selector, validator_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?)') ->execute([$userId, $selector, hash('sha256', $validator), utc_now(), utc_after($lifetime)]); setcookie(WS_REMEMBER_COOKIE, $selector . '.' . $validator, [ 'expires' => time() + $lifetime, 'path' => '/', 'secure' => is_https(), 'httponly' => true, 'samesite' => 'Lax', ]); } function auth_forget_remember(): void { $raw = $_COOKIE[WS_REMEMBER_COOKIE] ?? ''; if (is_string($raw) && str_contains($raw, '.')) { [$selector] = explode('.', $raw, 2); if ($selector !== '') { db()->prepare('DELETE FROM auth_tokens WHERE selector = ?')->execute([$selector]); } } if (isset($_COOKIE[WS_REMEMBER_COOKIE])) { setcookie(WS_REMEMBER_COOKIE, '', [ 'expires' => time() - 3600, 'path' => '/', 'secure' => is_https(), 'httponly' => true, 'samesite' => 'Lax', ]); unset($_COOKIE[WS_REMEMBER_COOKIE]); } } function auth_restore_from_remember(): void { $raw = $_COOKIE[WS_REMEMBER_COOKIE] ?? ''; if (!is_string($raw) || preg_match('/^([a-f0-9]{24})\.([a-f0-9]{64})$/', $raw, $m) !== 1) { return; } $stmt = db()->prepare( 'SELECT t.*, u.auth_epoch, u.status FROM auth_tokens t JOIN users u ON u.id = t.user_id WHERE t.selector = ? AND t.expires_at >= ? LIMIT 1' ); $stmt->execute([$m[1], utc_now()]); $token = $stmt->fetch(); if (!$token || !hash_equals((string) $token['validator_hash'], hash('sha256', $m[2]))) { auth_forget_remember(); return; } if ($token['status'] !== 'active') { auth_forget_remember(); return; } // Token rotieren, damit ein gestohlenes Cookie nur einmal nutzbar ist. db()->prepare('DELETE FROM auth_tokens WHERE id = ?')->execute([(int) $token['id']]); session_regenerate_id(true); $_SESSION['uid'] = (int) $token['user_id']; $_SESSION['epoch'] = (int) $token['auth_epoch']; $_SESSION['created'] = time(); $_SESSION['last_seen'] = time(); $_SESSION['csrf'] = bin2hex(random_bytes(32)); auth_issue_remember((int) $token['user_id']); }