27 lines
1.6 KiB
TypeScript
27 lines
1.6 KiB
TypeScript
import { PeppaError, startGoogleFlow } from "@peppa/core";
|
||
import { NextResponse, type NextRequest } from "next/server";
|
||
import { currentUser, GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { m } from "@peppa/shared/i18n";
|
||
|
||
/** Starts a Google login (PEP-90) or, from Settings (`purpose=link`, needs a session), linking. POST form → 303 to Google. */
|
||
export async function POST(req: NextRequest) {
|
||
const origin = await publicOrigin();
|
||
const form = await req.formData().catch(() => null);
|
||
const purpose = form?.get("purpose") === "link" ? "link" : "login";
|
||
const next = safeNext(String(form?.get("next") ?? ""));
|
||
const fail = (msg: string) => NextResponse.redirect(`${origin}${purpose === "link" ? "/settings" : "/login"}?error=${encodeURIComponent(msg)}`, 303);
|
||
try {
|
||
const user = purpose === "link" ? await currentUser() : null;
|
||
if (purpose === "link" && !user) return fail(m("Войдите, чтобы привязать Google"));
|
||
const flow = await startGoogleFlow(db, purpose, `${origin}/auth/google/callback`, user?.id ?? null);
|
||
const res = NextResponse.redirect(flow.url, 303);
|
||
res.cookies.set(GOOGLE_COOKIE, flow.state, googleCookieOptions(600));
|
||
// Where to go after login: a separate cookie value would leak into the URL, so keep it beside the state.
|
||
res.cookies.set(`${GOOGLE_COOKIE}_next`, next, googleCookieOptions(600));
|
||
return res;
|
||
} catch (e) {
|
||
return fail(e instanceof PeppaError ? e.message : m("Не удалось начать вход через Google"));
|
||
}
|
||
}
|