import { BASE_PATH } from "@/lib/base-path"; import { cookies } from "next/headers"; import { prisma } from "@/lib/db"; import { encryptToken } from "@/lib/crypto/tokenBox"; import { exchangeCode, OAUTH_STATE_COOKIE, verifyOAuthState } from "@/lib/facebook/oauth"; import { safeFacebookErrorMessage } from "@/lib/facebook/client"; import { audit } from "@/lib/audit"; import { htmlRedirect } from "@/lib/http"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; /** * Facebook redirects here cross-site, so the SameSite=Strict session cookie is * absent: identity comes from the signed Lax state cookie (listed under * SELF_AUTH_PREFIXES in src/proxy.ts). The response is an HTML hop rather than * a 302 so the follow-up navigation to /pages is same-site and the session * cookie is sent again. */ const hop = htmlRedirect; export async function GET(req: Request) { const url = new URL(req.url); const jar = await cookies(); const stateCookie = jar.get(OAUTH_STATE_COOKIE)?.value; jar.delete({ name: OAUTH_STATE_COOKIE, path: `${BASE_PATH}/api/facebook/oauth` }); const userId = await verifyOAuthState(stateCookie, url.searchParams.get("state")); if (!userId) return hop(`/pages?fb_error=${encodeURIComponent("ลิงก์เชื่อมหมดอายุหรือไม่ถูกต้อง ลองกดเชื่อมใหม่")}`); const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, isActive: true, globalRole: true } }); if (!user?.isActive || user.globalRole !== "SUPERADMIN") return hop("/pages?fb_error=forbidden"); const fbError = url.searchParams.get("error_description") ?? url.searchParams.get("error"); if (fbError) return hop(`/pages?fb_error=${encodeURIComponent(`Facebook: ${fbError}`)}`); const code = url.searchParams.get("code"); if (!code) return hop(`/pages?fb_error=${encodeURIComponent("ไม่ได้รับ code จาก Facebook")}`); try { const r = await exchangeCode(url.origin, code); const conn = await prisma.metaConnection.upsert({ where: { fbUserId: r.fbUserId }, create: { fbUserId: r.fbUserId, name: r.name, tokenCipher: encryptToken(r.token), scopes: r.scopes, expiresAt: r.expiresAt, connectedById: user.id }, update: { name: r.name, tokenCipher: encryptToken(r.token), scopes: r.scopes, expiresAt: r.expiresAt, connectedById: user.id }, }); await audit({ action: "META_LOGIN_CONNECTED", actorId: user.id, actorLabel: user.name || user.email, detail: { connectionId: conn.id, fbUser: r.name, scopes: r.scopes }, }); return hop("/pages?fb=connected"); } catch (e) { return hop(`/pages?fb_error=${encodeURIComponent(safeFacebookErrorMessage(e, "fb:oauth:callback"))}`); } }