# What does this PR do?


## Test Plan
# What does this PR do?


## Test Plan
# What does this PR do?


## Test Plan
This commit is contained in:
Eric Huang 2025-06-25 20:10:45 -07:00
parent 114946ae88
commit a4d84f7805
22 changed files with 821 additions and 38 deletions

View file

@ -0,0 +1,88 @@
import { NextRequest, NextResponse } from "next/server";
import { BACKEND_URL } from "@/lib/server-config";
async function proxyAuthRequest(request: NextRequest, method: string) {
try {
const url = new URL(request.url);
const pathSegments = url.pathname.split("/");
// Remove /api/auth from the path to get the actual auth path
// /api/auth/github/login -> /auth/github/login
const authPath = pathSegments.slice(3).join("/"); // Remove 'api' and 'auth' segments
const targetUrl = `${BACKEND_URL}/auth/${authPath}${url.search}`;
// Prepare headers (exclude host and other problematic headers)
const headers = new Headers();
request.headers.forEach((value, key) => {
// Skip headers that might cause issues in proxy
if (
!["host", "connection", "content-length"].includes(key.toLowerCase())
) {
headers.set(key, value);
}
});
const requestOptions: RequestInit = {
method,
headers,
// Don't follow redirects automatically - we need to handle them
redirect: "manual",
};
if (["POST", "PUT", "PATCH"].includes(method) && request.body) {
requestOptions.body = await request.text();
}
const response = await fetch(targetUrl, requestOptions);
// Handle redirects
if (response.status === 302 || response.status === 307) {
const location = response.headers.get("location");
if (location) {
// For external redirects (like GitHub OAuth), return the redirect
return NextResponse.redirect(location);
}
}
if (response.ok) {
const responseText = await response.text();
const proxyResponse = new NextResponse(responseText, {
status: response.status,
statusText: response.statusText,
});
response.headers.forEach((value, key) => {
if (!["connection", "transfer-encoding"].includes(key.toLowerCase())) {
proxyResponse.headers.set(key, value);
}
});
return proxyResponse;
}
const errorText = await response.text();
return new NextResponse(errorText, {
status: response.status,
statusText: response.statusText,
});
} catch (error) {
return NextResponse.json(
{
error: "Auth proxy request failed",
message: error instanceof Error ? error.message : "Unknown error",
backend_url: BACKEND_URL,
timestamp: new Date().toISOString(),
},
{ status: 500 },
);
}
}
export async function GET(request: NextRequest) {
return proxyAuthRequest(request, "GET");
}
export async function POST(request: NextRequest) {
return proxyAuthRequest(request, "POST");
}

View file

@ -1,9 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
// Get backend URL from environment variable or default to localhost for development
const BACKEND_URL =
process.env.LLAMA_STACK_BACKEND_URL ||
`http://localhost:${process.env.LLAMA_STACK_PORT || 8321}`;
import { BACKEND_URL } from "@/lib/server-config";
async function proxyRequest(request: NextRequest, method: string) {
try {
@ -16,8 +12,6 @@ async function proxyRequest(request: NextRequest, method: string) {
const apiPath = pathSegments.slice(2).join("/"); // Remove 'api' segment
const targetUrl = `${BACKEND_URL}/${apiPath}${url.search}`;
console.log(`Proxying ${method} ${url.pathname} -> ${targetUrl}`);
// Prepare headers (exclude host and other problematic headers)
const headers = new Headers();
request.headers.forEach((value, key) => {
@ -33,6 +27,7 @@ async function proxyRequest(request: NextRequest, method: string) {
const requestOptions: RequestInit = {
method,
headers,
redirect: apiPath.startsWith("auth/") ? "manual" : "follow",
};
// Add body for methods that support it
@ -43,6 +38,18 @@ async function proxyRequest(request: NextRequest, method: string) {
// Make the request to FastAPI backend
const response = await fetch(targetUrl, requestOptions);
// Handle redirects for auth routes
if (
response.type === "opaqueredirect" ||
response.status === 302 ||
response.status === 307
) {
const location = response.headers.get("location");
if (location) {
return NextResponse.redirect(location);
}
}
// Get response data
const responseText = await response.text();

View file

@ -0,0 +1,81 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/contexts/auth-context";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
export default function AuthCallbackPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { login } = useAuth();
const [error, setError] = useState<string | null>(null);
const [isProcessing, setIsProcessing] = useState(true);
useEffect(() => {
const processCallback = async () => {
// Get token from URL fragment (hash)
const hash = window.location.hash.substring(1); // Remove the #
const params = new URLSearchParams(hash);
const token = params.get("token");
if (!token) {
setError("Missing authentication token");
setIsProcessing(false);
return;
}
try {
// Store the token and decode user info from JWT
await login(token);
setIsProcessing(false);
} catch (err) {
setError("Failed to complete authentication");
setIsProcessing(false);
}
};
processCallback();
}, [searchParams, login]);
if (error) {
return (
<div className="flex items-center justify-center min-h-screen">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-red-600">Authentication Error</CardTitle>
<CardDescription>{error}</CardDescription>
</CardHeader>
<CardContent>
<Button onClick={() => router.push("/login")} className="w-full">
Back to Login
</Button>
</CardContent>
</Card>
</div>
);
}
return (
<div className="flex items-center justify-center min-h-screen">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>Authenticating...</CardTitle>
<CardDescription>
Please wait while we complete your login.
</CardDescription>
</CardHeader>
<CardContent className="flex justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
</CardContent>
</Card>
</div>
);
}

View file

@ -2,6 +2,9 @@ import type { Metadata } from "next";
import { ThemeProvider } from "@/components/ui/theme-provider";
import { Geist, Geist_Mono } from "next/font/google";
import { ModeToggle } from "@/components/ui/mode-toggle";
import { AuthProvider } from "@/contexts/auth-context";
import { UserMenu } from "@/components/auth/user-menu";
import { Toaster } from "@/components/ui/sonner";
import "./globals.css";
const geistSans = Geist({
@ -32,22 +35,26 @@ export default function Layout({ children }: { children: React.ReactNode }) {
enableSystem
disableTransitionOnChange
>
<SidebarProvider>
<AppSidebar />
<main className="flex flex-col flex-1">
{/* Header with aligned elements */}
<div className="flex items-center p-4 border-b">
<div className="flex-none">
<SidebarTrigger />
<AuthProvider>
<SidebarProvider>
<AppSidebar />
<main className="flex flex-col flex-1">
{/* Header with aligned elements */}
<div className="flex items-center p-4 border-b">
<div className="flex-none">
<SidebarTrigger />
</div>
<div className="flex-1 text-center"></div>
<div className="flex-none flex items-center gap-2">
<ModeToggle />
<UserMenu />
</div>
</div>
<div className="flex-1 text-center"></div>
<div className="flex-none">
<ModeToggle />
</div>
</div>
<div className="flex flex-col flex-1 p-4">{children}</div>
</main>
</SidebarProvider>
<div className="flex flex-col flex-1 p-4">{children}</div>
</main>
</SidebarProvider>
</AuthProvider>
<Toaster />
</ThemeProvider>
</body>
</html>

View file

@ -0,0 +1,6 @@
import { LoginPage } from "@/components/auth/login-page";
import { serverConfig } from "@/lib/server-config";
export default function LoginPageRoute() {
return <LoginPage backendUrl={serverConfig.backendUrl} />;
}

View file

@ -4,7 +4,7 @@ import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ChatCompletion } from "@/lib/types";
import { ChatCompletionDetailView } from "@/components/chat-completions/chat-completion-detail";
import { client } from "@/lib/client";
import { getClient } from "@/lib/client";
export default function ChatCompletionDetailPage() {
const params = useParams();
@ -27,7 +27,7 @@ export default function ChatCompletionDetailPage() {
setError(null);
setCompletionDetail(null);
try {
const response = await client.chat.completions.retrieve(id);
const response = await getClient().chat.completions.retrieve(id);
setCompletionDetail(response as ChatCompletion);
} catch (err) {
console.error(

View file

@ -5,7 +5,7 @@ import { useParams } from "next/navigation";
import type { ResponseObject } from "llama-stack-client/resources/responses/responses";
import { OpenAIResponse, InputItemListResponse } from "@/lib/types";
import { ResponseDetailView } from "@/components/responses/responses-detail";
import { client } from "@/lib/client";
import { getClient } from "@/lib/client";
export default function ResponseDetailPage() {
const params = useParams();
@ -59,6 +59,8 @@ export default function ResponseDetailPage() {
setResponseDetail(null);
setInputItems(null);
const client = getClient();
try {
const [responseResult, inputItemsResult] = await Promise.allSettled([
client.responses.retrieve(id),