39 lines
2.2 KiB
TypeScript
39 lines
2.2 KiB
TypeScript
import { completeEgovFlow, isUserAllowed, logEgovEvent, PeppaError } from "@peppa/core";
|
||
import { cookies } from "next/headers";
|
||
import { NextResponse, type NextRequest } from "next/server";
|
||
import { EGOV_COOKIE, egovCookieOptions, safeNext, sessionCookie } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||
|
||
/** Finishes a signed eGov flow: logs in by the IIN (PEP-71: registers an unknown one), or links it to the current account. */
|
||
export async function POST(req: NextRequest) {
|
||
const { next } = (await req.json().catch(() => ({}))) as { next?: string };
|
||
const handle = (await cookies()).get(EGOV_COOKIE)?.value ?? "";
|
||
const done = (body: object, status = 200) => {
|
||
const res = NextResponse.json(body, { status });
|
||
res.cookies.set(EGOV_COOKIE, "", egovCookieOptions(0));
|
||
return res;
|
||
};
|
||
try {
|
||
const r = await completeEgovFlow(db, handle);
|
||
// The handle lives only in the starter's httpOnly cookie, so a link flow is finished by the
|
||
// browser (and account) that started it.
|
||
if (r.purpose === "link") return done({ redirect: "/settings?egov=linked" });
|
||
if (!(await isUserAllowed(db, r.user))) {
|
||
await logEgovEvent(db, { ok: false, step: "complete", error: null, code: "not_allowed", purpose: "login", handle, userId: r.user.id });
|
||
return done({ error: m("Учётка отключена — обратитесь к администратору") }, 403);
|
||
}
|
||
await logEgovEvent(db, { ok: true, step: "complete", purpose: "login", handle, userId: r.user.id });
|
||
const res = done({ redirect: safeNext(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({ error: e instanceof PeppaError ? e.message : m("Не удалось войти через eGov") }, 400);
|
||
}
|
||
}
|