import { BASE_PATH, appUrl } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { getCurrentUser, isSuperadmin } from "@/lib/auth/user"; import { authorizeUrl, createOAuthState, OAUTH_STATE_COOKIE } from "@/lib/facebook/oauth"; import { safeFacebookErrorMessage } from "@/lib/facebook/client"; import { externalRedirect } from "@/lib/http"; /** SUPERADMIN only: redirects to the Facebook consent dialog. */ export async function GET(req: Request) { const origin = new URL(req.url).origin; const root = appUrl(origin); const user = await getCurrentUser(); if (!user || !isSuperadmin(user)) return NextResponse.redirect(`${root}/pages?fb_error=forbidden`); try { const { nonce, cookie } = await createOAuthState(user.id); const res = externalRedirect(authorizeUrl(origin, nonce)); res.cookies.set(OAUTH_STATE_COOKIE, cookie, { httpOnly: true, secure: process.env.NODE_ENV === "production", // Lax: must survive the top-level redirect back from facebook.com. sameSite: "lax", path: `${BASE_PATH}/api/facebook/oauth`, maxAge: 600, }); return res; } catch (e) { const msg = safeFacebookErrorMessage(e, "fb:oauth:start"); return NextResponse.redirect(`${root}/pages?fb_error=${encodeURIComponent(msg)}`); } }