import { CONNECTION_OAUTH_COOKIE, PeppaError, startConnectionOAuth } from "@peppa/core"; import { NextResponse, type NextRequest } from "next/server"; import { connOAuthCookieOptions, currentUser, publicOrigin } from "@/lib/auth"; import { db } from "@/lib/db"; import { m } from "@peppa/shared/i18n"; /** * PEP-252: «Войти через Google / GitHub» in «Подключения» (POST form: catalogId + level, or * connectionId for «Войти заново») → 303 to the service's sign-in page. The state goes into an * httpOnly cookie of this browser; the callback must bring the same state back. */ export async function POST(req: NextRequest) { const origin = await publicOrigin(); const form = await req.formData().catch(() => null); const fail = (msg: string) => NextResponse.redirect(`${origin}/connections?error=${encodeURIComponent(msg)}#add`, 303); const user = await currentUser(); if (!user) return NextResponse.redirect(`${origin}/login`, 303); try { const connectionId = Number(form?.get("connectionId") ?? ""); const flow = await startConnectionOAuth(db, user.id, { catalogId: String(form?.get("catalogId") ?? "") || null, connectionId: Number.isInteger(connectionId) && connectionId > 0 ? connectionId : null, level: String(form?.get("level") ?? "") || null, redirectUri: `${origin}/connections/oauth/callback`, }); const res = NextResponse.redirect(flow.url, 303); res.cookies.set(CONNECTION_OAUTH_COOKIE, flow.state, connOAuthCookieOptions(600)); return res; } catch (e) { return fail(e instanceof PeppaError ? e.message : m("Не удалось начать вход в сервис")); } }