86400 * 7, 'path' => '/', 'httponly' => true, 'secure' => true, 'samesite' => 'Lax', ]); session_start(); $authToken = $_GET['auth'] ?? ''; $rawRedirect = $_GET['redirect'] ?? '/'; $errorRedirect = isSafeRedirect($rawRedirect) ? $rawRedirect : '/'; if (!$authToken) { $_SESSION['auth_error'] = 'Missing authentication token.'; header('Location: ' . $errorRedirect); exit; } $checkUrl = 'https://auth.jakach.ch/api/auth/check_auth_key.php?auth_token=' . urlencode($authToken); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $checkUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($httpCode !== 200 || !$response) { $_SESSION['auth_error'] = "Auth server unreachable ($httpCode)"; header('Location: ' . $errorRedirect); exit; } $data = json_decode($response, true); if (!isset($data['status']) || $data['status'] !== 'success') { $_SESSION['auth_error'] = 'Authentication failed: ' . ($data['msg'] ?? 'Unknown error'); header('Location: ' . $errorRedirect); exit; } $userToken = $data['user_token'] ?? ''; $db = new Database(); $repo = new Repository($db); $allowedTokens = $repo->getAllowedUserTokens(); if (empty($allowedTokens)) { $bootstrapAllowed = filter_var(getenv('ALLOW_FIRST_USER_BOOTSTRAP') ?: 'false', FILTER_VALIDATE_BOOL); if (!$bootstrapAllowed) { $_SESSION['auth_error'] = 'No users are authorized for this system. Set allowed_user_tokens or enable first-user bootstrap during initial setup.'; header('Location: ' . $errorRedirect); exit; } $repo->setAllowedUserTokens([$userToken]); } elseif (!in_array($userToken, $allowedTokens, true)) { $_SESSION['auth_error'] = 'Your Jakach account is not authorized to access this system. Contact an administrator.'; header('Location: ' . $errorRedirect); exit; } session_regenerate_id(true); $_SESSION['loggedin'] = true; $_SESSION['username'] = $data['username'] ?? 'unknown'; $_SESSION['id'] = $data['id'] ?? ''; $_SESSION['email'] = $data['email'] ?? ''; $_SESSION['telegram_id'] = $data['telegram_id'] ?? ''; $_SESSION['user_token'] = $userToken; unset($_SESSION['auth_error']); $redirect = isSafeRedirect($rawRedirect) ? $rawRedirect : '/'; header('Location: ' . $redirect); exit;