Spaces:
Sleeping
Sleeping
Caner Giden commited on
Commit ·
68f2cea
1
Parent(s): d5f7ccd
B2: /me endpoint eklendi ve test UI'ı eklendi
Browse files- /api/me endpoint oluşturuldu (Core /me proxy)
- Authorization header desteği eklendi
- Ana sayfaya /me endpoint test UI'ı eklendi
- Key yokken 401, key varken user bilgisi dönüyor
Files changed (2)
- app/api/me/route.tsAdded+103
- app/page.tsx+98-21
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import { NextRequest, NextResponse } from "next/server";
/** * Server-side proxy endpoint for Core /me * /api/me → Core /me * Requires Authorization header for authenticated requests */export async function GET(request: NextRequest) { // Support both NEXT_PUBLIC_API_BASE (for compatibility) and CORE_API_BASE (server-only) const base = process.env.CORE_API_BASE || process.env.NEXT_PUBLIC_API_BASE; if (!base) { return NextResponse.json( { ok: false, error: "Core API base URL not configured. Set CORE_API_BASE or NEXT_PUBLIC_API_BASE environment variable." }, { status: 500 } ); }
// Extract Authorization header from request const authHeader = request.headers.get("authorization"); const coreUrl = `${base.replace(/\/$/, "")}/me`; const timeoutMs = 5000; // 5 second timeout
try { // Create abort controller for timeout const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
// Prepare headers for Core API request const headers: Record<string, string> = { "Content-Type": "application/json", }; // Forward Authorization header if present if (authHeader) { headers["Authorization"] = authHeader; }
const res = await fetch(coreUrl, { cache: "no-store", signal: controller.signal, headers, });
clearTimeout(timeoutId);
// Check if auth was successful based on response status // 401/403 typically means auth failed const authOk = res.status !== 401 && res.status !== 403; const authProvided = authHeader !== null;
// Try to parse JSON response (even if status is not ok, we still want to parse it) let data: any; const text = await res.text(); try { data = JSON.parse(text); } catch (parseError) { // If JSON parse fails, return raw text return NextResponse.json( { ok: false, error: "Core returned invalid JSON response", raw: text, status: res.status, }, { status: res.status } ); }
// Return response with status code from Core // If 401/403, Core will return error, we forward it return NextResponse.json({ ok: res.ok, status: res.status, data, }, { status: res.status }); } catch (e: any) { // Handle timeout and other errors if (e.name === "AbortError") { return NextResponse.json( { ok: false, error: `Core /me request timed out after ${timeoutMs}ms`, }, { status: 504 } ); }
return NextResponse.json( { ok: false, error: e?.message ?? "Failed to connect to Core service", details: process.env.NODE_ENV === "development" ? String(e) : undefined, }, { status: 502 } ); }}
4 unmodified lines567891010111213141415161718192021222324252627282930313233151617181920212223242526272829303132333435363738394041424344454647484950515290 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082094 unmodified lines
export default function Home() { const [health, setHealth] = useState<any>(null); const [meData, setMeData] = useState<any>(null); const [hasApiKey, setHasApiKey] = useState<boolean | null>(null);
useEffect(() => { const fetchData = async () => { // Check if API key exists (client-side only) setHasApiKey(getApiKey() !== null);
(async () => { try { const apiKey = getApiKey(); const headers: Record<string, string> = {};
// Add Authorization header if API key exists if (apiKey) { headers["Authorization"] = `Bearer ${apiKey}`; }
const res = await fetch("/api/core-health", { cache: "no-store", headers, }); const data = await res.json(); setHealth(data); } catch (e: any) { setHealth({ ok: false, error: e?.message ?? "fetch failed" }); } })(); const apiKey = getApiKey(); const headers: Record<string, string> = {};
// Add Authorization header if API key exists if (apiKey) { headers["Authorization"] = `Bearer ${apiKey}`; }
// Fetch health check try { const res = await fetch("/api/core-health", { cache: "no-store", headers, }); const data = await res.json(); setHealth(data); } catch (e: any) { setHealth({ ok: false, error: e?.message ?? "fetch failed" }); }
// Fetch /me endpoint try { const res = await fetch("/api/me", { cache: "no-store", headers, }); const data = await res.json(); setMeData({ ...data, httpStatus: res.status }); } catch (e: any) { setMeData({ ok: false, error: e?.message ?? "fetch failed" }); } };
useEffect(() => { fetchData(); }, []);
// Determine auth status90 unmodified lines Burada <code>ok: true</code> ve <code>data.db_ok: true</code>{" "} görüyorsan Studio → Core bağlantısı tamam. </p>
<div style={{ marginTop: 32 }}> <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12, }} > <h2 style={{ margin: 0, fontSize: 18 }}>User Info (via /api/me):</h2> <button onClick={fetchData} style={{ padding: "6px 12px", fontSize: 12, backgroundColor: "#0070f3", color: "white", border: "none", borderRadius: 4, cursor: "pointer", }} > Refresh </button> </div>
<pre style={{ background: "#111", color: "#0f0", padding: 16, borderRadius: 8, whiteSpace: "pre-wrap", }} > {meData === null ? "Loading..." : JSON.stringify(meData, null, 2)} </pre>
{meData && ( <p style={{ fontSize: 14, color: "#666", marginTop: 8 }}> {meData.httpStatus === 401 ? ( <> <strong>Status 401:</strong> Key yokken veya geçersiz key ile{" "} <code>/me</code> çağrısı 401 gösteriyor. ✓ </> ) : meData.ok && meData.data ? ( <> <strong>Status {meData.httpStatus}:</strong> Key varken user bilgisi dönüyor. ✓ </> ) : ( <> <strong>Status {meData.httpStatus}:</strong> {meData.error || "Unknown error"} </> )} </p> )} </div> </main> );}app/api/me/route.tsAdded+103
app/page.tsx+98-21