32768, 'time_cost' => 3, 'threads' => 2, ]); } 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' => 2, ]); } 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 $user; } } $uid = (int) $uid; $stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1'); $stmt->execute([$uid]); $row = $stmt->fetch(); if (!$row || $row['status'] !== 'active') { auth_clear_session(); return $user; } if ((int) ($_SESSION['epoch'] ?? 0) !== (int) $row['auth_epoch']) { auth_clear_session(); return $user; } $now = time(); $idleLimit = (int) config('app.session_idle_seconds', 1209600); $absoluteLimit = (int) config('app.session_absolute_seconds', 2592000); $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 $user; } 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)); $stmt = db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?'); $stmt->execute([utc_now(), (int) $user['id']]); if ($remember) { auth_issue_remember((int) $user['id']); } audit('user.login', 'user', (int) $user['id'], 'Anmeldung', (int) $user['id']); } function auth_clear_session(): void { $_SESSION = []; if (session_status() === PHP_SESSION_ACTIVE) { session_regenerate_id(true); } } function auth_logout(): void { $user = auth_user(); if ($user) { audit('user.logout', 'user', (int) $user['id'], '', (int) $user['id']); } auth_forget_remember(); auth_clear_session(); session_destroy(); } function auth_require_login(): array { $user = auth_user(); if ($user === null) { $target = (string) ($_SERVER['REQUEST_URI'] ?? '/'); redirect('/login?next=' . rawurlencode($target)); } return $user; } function auth_require_admin(): array { $user = auth_require_login(); if ($user['role'] !== 'admin') { abort_page(403, 'Dieser Bereich ist nur für Administratoren.'); } return $user; } function auth_is_admin(?array $user): bool { return $user !== null && ($user['role'] ?? '') === 'admin'; } function auth_attempt(string $login, string $password): array { $login = trim($login); $ip = client_ip(); $window = (int) config('app.login_window_seconds', 900); $maxUser = (int) config('app.login_max_per_user', 5); $maxIp = (int) config('app.login_max_per_ip', 10); $since = gmdate('Y-m-d H:i:s', time() - $window); $stmt = db()->prepare( 'SELECT SUM(username = ?) AS by_user, SUM(ip = ?) AS by_ip, MIN(created_at) AS first_seen FROM login_attempts WHERE success = 0 AND created_at >= ? AND (username = ? OR ip = ?)' ); $stmt->execute([$login, $ip, $since, $login, $ip]); $window_row = $stmt->fetch() ?: []; $byUser = (int) ($window_row['by_user'] ?? 0); $byIp = (int) ($window_row['by_ip'] ?? 0); if ($byUser >= $maxUser || $byIp >= $maxIp) { $first = strtotime((string) ($window_row['first_seen'] ?? 'now') . ' UTC'); $retry = max(60, (int) $first + $window - time()); return [ 'ok' => false, 'error' => 'Zu viele Fehlversuche. Bitte in ' . max(1, (int) ceil($retry / 60)) . ' Minuten erneut versuchen.', 'retry' => $retry, ]; } $stmt = db()->prepare('SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1'); $stmt->execute([$login, $login]); $user = $stmt->fetch() ?: null; $hash = $user['password_hash'] ?? HUB_DUMMY_HASH; $valid = password_verify($password, $hash); $stmt = db()->prepare( 'INSERT INTO login_attempts (username, ip, success, created_at) VALUES (?, ?, ?, ?)' ); $stmt->execute([mb_substr($login, 0, 190, 'UTF-8'), $ip, $valid ? 1 : 0, utc_now()]); if (random_int(1, 100) === 1) { db()->prepare('DELETE FROM login_attempts WHERE created_at < ? LIMIT 1000') ->execute([gmdate('Y-m-d H:i:s', time() - 30 * 86400)]); } if (!$user || !$valid) { return ['ok' => false, 'error' => 'Benutzername oder Passwort ist falsch.', 'retry' => 0]; } if ($user['status'] !== 'active') { return ['ok' => false, 'error' => 'Dieses Konto ist deaktiviert.', 'retry' => 0]; } if (password_needs_upgrade((string) $user['password_hash'])) { db()->prepare('UPDATE users SET password_hash = ? WHERE id = ?') ->execute([hash_password($password), (int) $user['id']]); } return ['ok' => true, 'user' => $user, 'error' => '', 'retry' => 0]; } function auth_next_url(string $fallback = '/'): string { $next = (string) ($_POST['next'] ?? $_GET['next'] ?? ''); if ($next === '' || $next[0] !== '/' || str_starts_with($next, '//') || str_starts_with($next, '/api/') ) { return $fallback; } return $next; } function auth_issue_remember(int $userId): void { $selector = bin2hex(random_bytes(12)); $validator = bin2hex(random_bytes(32)); $seconds = (int) config('app.remember_seconds', 2592000); $stmt = db()->prepare( 'INSERT INTO remember_tokens (user_id, selector, validator_hash, created_at, expires_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?, ?)' ); $stmt->execute([ $userId, $selector, hash('sha256', $validator), utc_now(), utc_after($seconds), user_agent(), client_ip(), ]); setcookie(HUB_REMEMBER_COOKIE, $selector . ':' . $validator, [ 'expires' => time() + $seconds, 'path' => '/', 'secure' => is_https(), 'httponly' => true, 'samesite' => 'Lax', ]); } function auth_restore_from_remember(): void { $cookie = (string) ($_COOKIE[HUB_REMEMBER_COOKIE] ?? ''); if ($cookie === '' || substr_count($cookie, ':') !== 1) { return; } [$selector, $validator] = explode(':', $cookie, 2); if (strlen($selector) !== 24 || strlen($validator) !== 64) { return; } $stmt = db()->prepare( 'SELECT rt.*, u.* FROM remember_tokens rt JOIN users u ON u.id = rt.user_id WHERE rt.selector = ? AND rt.expires_at > ? LIMIT 1' ); $stmt->execute([$selector, utc_now()]); $row = $stmt->fetch(); if (!$row || !hash_equals((string) $row['validator_hash'], hash('sha256', $validator))) { return; } if ($row['status'] !== 'active') { return; } db()->prepare('DELETE FROM remember_tokens WHERE id = ?')->execute([(int) $row['id']]); $_SESSION['uid'] = (int) $row['user_id']; $_SESSION['epoch'] = (int) $row['auth_epoch']; $_SESSION['created'] = time(); $_SESSION['last_seen'] = time(); $_SESSION['csrf'] = bin2hex(random_bytes(32)); session_regenerate_id(true); auth_issue_remember((int) $row['user_id']); db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?') ->execute([utc_now(), (int) $row['user_id']]); audit('user.login_remember', 'user', (int) $row['user_id'], '', (int) $row['user_id']); } function auth_forget_remember(): void { $cookie = (string) ($_COOKIE[HUB_REMEMBER_COOKIE] ?? ''); if (str_contains($cookie, ':')) { [$selector] = explode(':', $cookie, 2); if (strlen($selector) === 24) { db()->prepare('DELETE FROM remember_tokens WHERE selector = ?')->execute([$selector]); } } if (isset($_COOKIE[HUB_REMEMBER_COOKIE])) { setcookie(HUB_REMEMBER_COOKIE, '', [ 'expires' => time() - 3600, 'path' => '/', 'secure' => is_https(), 'httponly' => true, 'samesite' => 'Lax', ]); } } function auth_revoke_sessions(int $userId): void { db()->prepare('UPDATE users SET auth_epoch = auth_epoch + 1 WHERE id = ?')->execute([$userId]); db()->prepare('DELETE FROM remember_tokens WHERE user_id = ?')->execute([$userId]); db()->prepare('DELETE FROM api_tokens WHERE user_id = ?')->execute([$userId]); if ((int) ($_SESSION['uid'] ?? 0) === $userId) { $stmt = db()->prepare('SELECT auth_epoch FROM users WHERE id = ?'); $stmt->execute([$userId]); $epoch = $stmt->fetchColumn(); if ($epoch !== false) { $_SESSION['epoch'] = (int) $epoch; session_regenerate_id(true); } } } function audit( string $action, ?string $subjectType = null, ?int $subjectId = null, string $detail = '', ?int $actorId = null ): void { if ($actorId === null) { $current = auth_user(); $actorId = $current ? (int) $current['id'] : null; } $stmt = db()->prepare( 'INSERT INTO audit_log (actor_id, action, subject_type, subject_id, detail, ip, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)' ); $stmt->execute([ $actorId, mb_substr($action, 0, 64, 'UTF-8'), $subjectType, $subjectId, mb_substr($detail, 0, 255, 'UTF-8'), client_ip(), utc_now(), ]); }