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)); $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']); } db()->prepare('DELETE FROM login_attempts WHERE name_key = ?')->execute([auth_name_key((string) $user['first_name'], (string) $user['last_name'])]); } 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 Administratoren.'); } return $user; } function auth_name_key(string $first, string $last): string { return mb_strtolower(trim($first) . ' ' . trim($last), 'UTF-8'); } function auth_find_by_name(string $first, string $last): ?array { $stmt = db()->prepare('SELECT * FROM users WHERE first_name = ? AND last_name = ? LIMIT 1'); $stmt->execute([trim($first), trim($last)]); $row = $stmt->fetch(); return $row ?: null; } function auth_is_locked_out(string $first, string $last): bool { $window = (int) config('app.login_window_seconds', 900); $maxIp = (int) config('app.login_max_per_ip', 15); $maxName = (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 name_key = ? AND attempted_at >= ?'); $stmt->execute([auth_name_key($first, $last), utc_after(-$window)]); return (int) $stmt->fetchColumn() >= $maxName; } function auth_record_failure(string $first, string $last): void { $stmt = db()->prepare('INSERT INTO login_attempts (ip, name_key, attempted_at) VALUES (?, ?, ?)'); $stmt->execute([client_ip(), auth_name_key($first, $last), utc_now()]); // Tabelle klein halten; nur das Ratenfenster ist relevant. $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 $first, string $last, string $password): array { if (auth_is_locked_out($first, $last)) { throw new RuntimeException('locked'); } $user = auth_find_by_name($first, $last); $hash = $user['password_hash'] ?? DIC_DUMMY_HASH; $ok = password_verify($password, $hash); if (!$user || !$ok) { auth_record_failure($first, $last); throw new RuntimeException('invalid'); } if ($user['status'] !== 'active') { auth_record_failure($first, $last); 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]); } /* ------------------------------------------------------ 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()]); $stmt = db()->prepare('INSERT INTO auth_tokens (user_id, selector, validator_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?)'); $stmt->execute([$userId, $selector, hash('sha256', $validator), utc_now(), utc_after($lifetime)]); setcookie(DIC_REMEMBER_COOKIE, $selector . '.' . $validator, [ 'expires' => time() + $lifetime, 'path' => '/', 'secure' => is_https(), 'httponly' => true, 'samesite' => 'Lax', ]); } function auth_forget_remember(): void { $raw = $_COOKIE[DIC_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[DIC_REMEMBER_COOKIE])) { setcookie(DIC_REMEMBER_COOKIE, '', [ 'expires' => time() - 3600, 'path' => '/', 'secure' => is_https(), 'httponly' => true, 'samesite' => 'Lax', ]); unset($_COOKIE[DIC_REMEMBER_COOKIE]); } } function auth_restore_from_remember(): void { $raw = $_COOKIE[DIC_REMEMBER_COOKIE] ?? ''; if (!is_string($raw) || !preg_match('/^([a-f0-9]{24})\.([a-f0-9]{64})$/', $raw, $m)) { return; } $stmt = db()->prepare( 'SELECT t.*, u.auth_epoch, u.status, u.must_change_password 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']); } function auth_can_manage(User|null|array $user): bool { return is_array($user) && ($user['role'] ?? '') === 'admin'; } function auth_employee_id(array $user): int { return (int) ($user['employee_id'] ?? 0); } /** Offene Erinnerungen, die den Benutzer betreffen (für die Navigation). */ function auth_reminder_badge(array $user): int { return reminder_open_count($user, add_days(today_iso(), 7)); }