38 lines
2.2 KiB
TypeScript
38 lines
2.2 KiB
TypeScript
import { completeGoogleFlow, isUserAllowed, PeppaError } from "@peppa/core";
|
||
import { cookies } from "next/headers";
|
||
import { NextResponse, type NextRequest } from "next/server";
|
||
import { GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext, sessionCookie } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||
|
||
/** Google redirects here (PEP-90): checks state against the browser's cookie, then logs in, registers or links. */
|
||
export async function GET(req: NextRequest) {
|
||
const origin = await publicOrigin();
|
||
const jar = await cookies();
|
||
const cookieState = jar.get(GOOGLE_COOKIE)?.value ?? "";
|
||
const next = safeNext(jar.get(`${GOOGLE_COOKIE}_next`)?.value);
|
||
const q = req.nextUrl.searchParams;
|
||
const done = (path: string, error?: string) => {
|
||
const res = NextResponse.redirect(`${origin}${path}${error ? `${path.includes("?") ? "&" : "?"}error=${encodeURIComponent(error)}` : ""}`, 303);
|
||
res.cookies.set(GOOGLE_COOKIE, "", googleCookieOptions(0));
|
||
res.cookies.set(`${GOOGLE_COOKIE}_next`, "", googleCookieOptions(0));
|
||
return res;
|
||
};
|
||
if (q.get("error")) return done("/login", q.get("error") === "access_denied" ? m("Вход через Google отменён") : m("Google отказал во входе"));
|
||
try {
|
||
const r = await completeGoogleFlow(db, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState });
|
||
if (r.purpose === "link") return done("/settings?google=linked");
|
||
if (!(await isUserAllowed(db, r.user))) return done("/login", m("Учётка отключена — обратитесь к администратору"));
|
||
const res = done(next);
|
||
const c = sessionCookie(r.user.id);
|
||
res.cookies.set(c.name, c.value, c.options);
|
||
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
|
||
const lang = await adoptLocale(r.user.id, req.cookies.get(LOCALE_COOKIE)?.value);
|
||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||
return res;
|
||
} catch (e) {
|
||
return done("/login", e instanceof PeppaError ? e.message : m("Не удалось войти через Google"));
|
||
}
|
||
}
|