gts-x / src /lib /api-auth.ts
JAMES HAN
Initial commit β€” GTS Modern subtitle converter
dff41a8
Raw
History Blame Contribute Delete
1.19 kB
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { skipAuth } from "@/lib/auth-mock";
/**
* Dual auth check for API routes:
* 1. If NEXT_PUBLIC_SKIP_AUTH=true β†’ allow (dev mode)
* 2. If X-API-Key header matches API_KEY env β†’ allow (Gradio server-to-server)
* 3. If valid browser session cookie β†’ allow (Next.js UI)
* 4. Otherwise β†’ 401 Unauthorized
*
* Returns null if authorized, or a 401 Response to return early.
*/
export async function requireAuth(request: NextRequest): Promise<Response | null> {
// Dev mode bypass
if (skipAuth) return null;
// API key auth (for Gradio / external clients)
const apiKey = request.headers.get("x-api-key");
const expectedKey = process.env.API_KEY;
if (apiKey && expectedKey && apiKey === expectedKey) return null;
// Browser session auth (for Next.js UI)
try {
const session = await auth.api.getSession({
headers: await headers(),
});
if (session) return null;
} catch {
// Session check failed β€” fall through to 401
}
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}