Ядро (обновление токенов, «Войти заново», отзыв в сервисе), экран «Подключения», тексты ru/kk/en, мок и тесты. Пересобрано на main после PEP-251/258: миграция теперь 0033_access_hub_oauth, маскировка ответа — connectionKeyForms от текущего токена, проверка подключений принимает notify вместе с drivers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
37 lines
1.9 KiB
TypeScript
37 lines
1.9 KiB
TypeScript
import { checkConnection, completeConnectionOAuth, CONNECTION_OAUTH_COOKIE, OAUTH_ERROR_TEXT, PeppaError } from "@peppa/core";
|
||
import { cookies } from "next/headers";
|
||
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: the service sends the browser back here with code and state. The state must equal this
|
||
* browser's cookie and the flow must belong to the person signed in now; then the code is
|
||
* exchanged and the connection checked. Code and state never stay in the address: 303 to
|
||
* /connections without them.
|
||
*/
|
||
export async function GET(req: NextRequest) {
|
||
const origin = await publicOrigin();
|
||
const jar = await cookies();
|
||
const cookieState = jar.get(CONNECTION_OAUTH_COOKIE)?.value ?? "";
|
||
const q = req.nextUrl.searchParams;
|
||
const go = (path: string) => {
|
||
const res = NextResponse.redirect(`${origin}${path}`, 303);
|
||
res.cookies.set(CONNECTION_OAUTH_COOKIE, "", connOAuthCookieOptions(0));
|
||
return res;
|
||
};
|
||
const fail = (msg: string) => go(`/connections?error=${encodeURIComponent(msg)}`);
|
||
const user = await currentUser();
|
||
if (!user) return go("/login");
|
||
if (q.get("error")) return fail(q.get("error") === "access_denied" ? OAUTH_ERROR_TEXT.denied : OAUTH_ERROR_TEXT.failed);
|
||
try {
|
||
const r = await completeConnectionOAuth(db, user.id, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState });
|
||
const chk = await checkConnection(db, user.id, r.connectionId).catch(() => null);
|
||
const word = !chk ? "down" : chk.status;
|
||
return go(`/connections?${r.created ? "created" : "checked"}=${r.connectionId}&check=${word}&signed=1#c${r.connectionId}`);
|
||
} catch (e) {
|
||
return fail(e instanceof PeppaError ? e.message : m("Не удалось войти в сервис"));
|
||
}
|
||
}
|