PEP-195: привязка Gmail к учётке eGov объединяет учётки
Кто сначала вошёл через Google, получил отдельную учётку, и привязать этот Google к учётке eGov было нельзя. Теперь привязка объединяет их: проекты, участие в проектах, подключённые подписки, Telegram и свой бот переходят в учётку eGov, старая отключается (core/merge-users.ts). Учётка со своим eGov или Gitea не объединяется. Ошибка привязки возвращается в «Настройки» (раньше уходила на /login, откуда вошедшего перебрасывало на Главную, и текст терялся). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4619e197c9
commit
d894f2d7cb
@ -1,4 +1,4 @@
|
||||
import { completeGoogleFlow, isUserAllowed, PeppaError } from "@peppa/core";
|
||||
import { completeGoogleFlow, googleFlowPurpose, 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";
|
||||
@ -19,7 +19,9 @@ export async function GET(req: NextRequest) {
|
||||
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 отказал во входе"));
|
||||
// A link starts in Settings and its errors go back there: /login sends a signed-in user home and the error is lost (PEP-195).
|
||||
const failPath = (await googleFlowPurpose(db, q.get("state") ?? "")) === "link" ? "/settings" : "/login";
|
||||
if (q.get("error")) return done(failPath, 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");
|
||||
@ -32,6 +34,6 @@ export async function GET(req: NextRequest) {
|
||||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||||
return res;
|
||||
} catch (e) {
|
||||
return done("/login", e instanceof PeppaError ? e.message : m("Не удалось войти через Google"));
|
||||
return done(failPath, e instanceof PeppaError ? e.message : m("Не удалось войти через Google"));
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// accounts are never merged by e-mail. State lives in `settings` (one-shot, 10 min) and in an
|
||||
// httpOnly cookie of the starting browser, so a forged or replayed callback is refused before
|
||||
// Google is contacted. Tokens are not stored.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
import { createHash, randomBytes, randomInt } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
@ -13,6 +13,7 @@ import { PeppaError } from "./errors.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { getUser, type User } from "./users.ts";
|
||||
import { announceNewUser } from "./new-users.ts";
|
||||
import { mergeUserInto } from "./merge-users.ts";
|
||||
|
||||
export const GOOGLE_FLOW_TTL_MS = 10 * 60_000;
|
||||
export type GooglePurpose = "login" | "link";
|
||||
@ -158,10 +159,24 @@ export async function registerGoogleUser(db: Db, identity: GoogleIdentity): Prom
|
||||
throw new PeppaError(tr("Не удалось создать пользователя"));
|
||||
}
|
||||
|
||||
/** Which flow a Google callback belongs to, without spending it — so a failed link lands back in Settings. */
|
||||
export async function googleFlowPurpose(db: Db, state: string): Promise<GooglePurpose | null> {
|
||||
if (!state) return null;
|
||||
return (await getSetting<Flow>(db, flowKey(state)))?.purpose ?? null;
|
||||
}
|
||||
|
||||
/** Links a Google account to `userId`. One Google account — one Peppa account. */
|
||||
export async function linkGoogle(db: Db, userId: number, identity: GoogleIdentity): Promise<User> {
|
||||
const [other] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
|
||||
if (other && other.id !== userId) throw new PeppaError(tr("Этот Google-аккаунт уже привязан к другой учётке"));
|
||||
if (other && other.id !== userId) {
|
||||
// PEP-195: the Google account already has its own Peppa account (the person logged in with Google
|
||||
// before) — merge it into this one: for the platform it is one person. An account with its own
|
||||
// eGov or Gitea identity is someone else's: never merged here.
|
||||
if (other.egovIin || other.giteaId > 0) {
|
||||
throw new PeppaError(tr("Этот Google-аккаунт уже входит в другую учётку ({login}). Чтобы объединить учётки, обратитесь к администратору.", { login: asIs(other.login) }));
|
||||
}
|
||||
await mergeUserInto(db, other.id, userId);
|
||||
}
|
||||
await db.update(users).set({ googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() }).where(eq(users.id, userId));
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) throw new PeppaError(tr("Пользователь не найден"));
|
||||
|
||||
54
packages/core/src/merge-users.ts
Normal file
54
packages/core/src/merge-users.ts
Normal file
@ -0,0 +1,54 @@
|
||||
// PEP-195: one person — one account. Someone who first logged in with Google got a separate account;
|
||||
// linking that Google to their main (eGov) account merges the two: projects, project membership,
|
||||
// subscriptions they connected, Telegram and their own bot move to the main account, the old one
|
||||
// is switched off (its history stays, attributed to the old login).
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
|
||||
/** Moves everything the person works with from account `fromId` to `toId` and disables `fromId`. One transaction. */
|
||||
export async function mergeUserInto(db: Db, fromId: number, toId: number): Promise<void> {
|
||||
if (fromId === toId) return;
|
||||
const [from] = await db.select().from(users).where(eq(users.id, fromId));
|
||||
const [to] = await db.select().from(users).where(eq(users.id, toId));
|
||||
if (!from || !to) return;
|
||||
const moveTelegram = !to.telegramChatId && !!from.telegramChatId;
|
||||
const moveBot = !to.telegramBotTokenEnc && !!from.telegramBotTokenEnc;
|
||||
db.transaction((tx) => {
|
||||
tx.run(sql`UPDATE projects SET owner_id = ${toId} WHERE owner_id = ${fromId}`);
|
||||
// Membership: one row per project, none in the main account's own projects.
|
||||
tx.run(sql`INSERT OR IGNORE INTO project_members (project_id, user_id, added_by, created_at)
|
||||
SELECT project_id, ${toId}, added_by, created_at FROM project_members WHERE user_id = ${fromId}`);
|
||||
tx.run(sql`DELETE FROM project_members WHERE user_id = ${fromId}`);
|
||||
tx.run(sql`DELETE FROM project_members WHERE user_id = ${toId} AND project_id IN (SELECT id FROM projects WHERE owner_id = ${toId})`);
|
||||
tx.run(sql`UPDATE project_invites SET invited_by = ${toId} WHERE invited_by = ${fromId}`);
|
||||
tx.run(sql`UPDATE subscriptions SET created_by = ${toId} WHERE created_by = ${fromId}`);
|
||||
tx.run(sql`UPDATE subscription_pools SET created_by = ${toId} WHERE created_by = ${fromId}`);
|
||||
tx.run(sql`UPDATE chats SET user_id = ${toId} WHERE user_id = ${fromId} AND NOT EXISTS (SELECT 1 FROM chats WHERE user_id = ${toId})`);
|
||||
if (moveBot) tx.run(sql`UPDATE chats SET tg_bot_user_id = ${toId} WHERE tg_bot_user_id = ${fromId}`);
|
||||
// The old account lets go first: Telegram chat and Google identity are unique.
|
||||
tx.update(users)
|
||||
.set({
|
||||
googleSub: null,
|
||||
googleEmail: null,
|
||||
googleLinkedAt: null,
|
||||
telegramChatId: null,
|
||||
telegramUserId: null,
|
||||
telegramUsername: null,
|
||||
telegramPairedAt: null,
|
||||
telegramBotTokenEnc: null,
|
||||
telegramBotUsername: null,
|
||||
disabledAt: new Date(),
|
||||
})
|
||||
.where(eq(users.id, fromId))
|
||||
.run();
|
||||
if (moveTelegram || moveBot) {
|
||||
tx.update(users)
|
||||
.set({
|
||||
...(moveTelegram ? { telegramChatId: from.telegramChatId, telegramUserId: from.telegramUserId, telegramUsername: from.telegramUsername, telegramPairedAt: from.telegramPairedAt } : {}),
|
||||
...(moveBot ? { telegramBotTokenEnc: from.telegramBotTokenEnc, telegramBotUsername: from.telegramBotUsername } : {}),
|
||||
})
|
||||
.where(eq(users.id, toId))
|
||||
.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -298,7 +298,7 @@ export const bot: Dict = {
|
||||
"Google не подтвердил вход — попробуйте ещё раз": "Google did not confirm the sign-in — please try again",
|
||||
"Google не вернул профиль": "Google didn't return a profile",
|
||||
"Почта в Google не подтверждена": "The Google email isn't verified",
|
||||
"Этот Google-аккаунт уже привязан к другой учётке": "This Google account is already linked to another account",
|
||||
"Этот Google-аккаунт уже входит в другую учётку ({login}). Чтобы объединить учётки, обратитесь к администратору.": "This Google account already belongs to another account ({login}). To merge the accounts, contact the administrator.",
|
||||
"Это единственный способ входа — сначала привяжите eGov": "This is your only sign-in method — link eGov first",
|
||||
"Неверный логин или пароль": "Wrong login or password",
|
||||
"Слишком много попыток входа — попробуйте через 15 минут": "Too many sign-in attempts — try again in 15 minutes",
|
||||
|
||||
@ -297,7 +297,7 @@ export const bot: Dict = {
|
||||
"Google не подтвердил вход — попробуйте ещё раз": "Google кіруді растамады — қайталап көріңіз",
|
||||
"Google не вернул профиль": "Google профильді қайтармады",
|
||||
"Почта в Google не подтверждена": "Google поштасы расталмаған",
|
||||
"Этот Google-аккаунт уже привязан к другой учётке": "Бұл Google-аккаунт басқа тіркелгіге байланған",
|
||||
"Этот Google-аккаунт уже входит в другую учётку ({login}). Чтобы объединить учётки, обратитесь к администратору.": "Бұл Google-аккаунт басқа тіркелгіге ({login}) кіреді. Тіркелгілерді біріктіру үшін әкімшіге жазыңыз.",
|
||||
"Это единственный способ входа — сначала привяжите eGov": "Бұл — кірудің жалғыз тәсілі — алдымен eGov байлаңыз",
|
||||
"Неверный логин или пароль": "Логин немесе құпиясөз қате",
|
||||
"Слишком много попыток входа — попробуйте через 15 минут": "Кіру әрекеттері тым көп — 15 минуттан кейін қайталап көріңіз",
|
||||
|
||||
@ -112,7 +112,7 @@ describe("Google login", () => {
|
||||
await core.setUserDisabled(db, r.user.id, false);
|
||||
});
|
||||
|
||||
test("link Google to an eGov account, taken account refused, unlink guard", async () => {
|
||||
test("link Google to an eGov account, an earlier Google-only account merges in (PEP-195), unlink guard", async () => {
|
||||
const egov = await core.registerEgovUser(db, { iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" });
|
||||
await assert.rejects(core.startGoogleFlow(db, "link", REDIRECT, null), /после входа/);
|
||||
google.account = { sub: "g-2002", email: "asel@example.com", email_verified: true };
|
||||
@ -125,15 +125,38 @@ describe("Google login", () => {
|
||||
const r2 = await core.completeGoogleFlow(db, { state: again.state, code: again.code, cookieState: again.f.state });
|
||||
assert.equal(r2.user.id, egov.id, "Google now leads into the eGov account");
|
||||
|
||||
// g-1001 belongs to anna.petrova: the eGov account cannot take it.
|
||||
// g-1001 is anna.petrova's own Google-only account (she logged in with Google first) with a project
|
||||
// and Telegram: linking that Google to the eGov account merges the two (PEP-195).
|
||||
const { users } = await import("@peppa/db");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
const [anna] = await db.select().from(users).where(eq(users.googleSub, "g-1001"));
|
||||
const annaProject = await core.createProject(db, { slug: "mock-anna", key: "ANNA", name: "Проект Анны", giteaOwner: "x", workspacePath: "/tmp/mock-anna", ownerId: anna!.id });
|
||||
await db.update(users).set({ telegramChatId: 777001, telegramUsername: "anna" }).where(eq(users.id, anna!.id));
|
||||
google.account = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true };
|
||||
const t = await login("link", egov.id);
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: t.state, code: t.code, cookieState: t.f.state }), /уже привязан/);
|
||||
const merged = await core.completeGoogleFlow(db, { state: t.state, code: t.code, cookieState: t.f.state });
|
||||
assert.equal(merged.user.id, egov.id);
|
||||
assert.equal(merged.user.googleSub, "g-1001");
|
||||
assert.equal(merged.user.telegramChatId, 777001, "Telegram moves to the main account");
|
||||
assert.equal((await core.getProject(db, "ANNA"))!.ownerId, egov.id, "projects move to the main account");
|
||||
const old = (await core.getUser(db, anna!.id))!;
|
||||
assert.ok(old.disabledAt && !old.googleSub && !old.telegramChatId, "the old account is switched off");
|
||||
const back = await login();
|
||||
assert.equal((await core.completeGoogleFlow(db, { state: back.state, code: back.code, cookieState: back.f.state })).user.id, egov.id);
|
||||
|
||||
// An account with its own eGov is another person: not merged.
|
||||
const other = await core.registerEgovUser(db, { iin: "850505400008", name: "ИВАНОВА АЙГЕРИМ" });
|
||||
await core.linkGoogle(db, other.id, { sub: "g-4004", email: "aigerim@example.com", name: null });
|
||||
google.account = { sub: "g-4004", email: "aigerim@example.com", email_verified: true };
|
||||
const x = await login("link", egov.id);
|
||||
await assert.rejects(core.completeGoogleFlow(db, { state: x.state, code: x.code, cookieState: x.f.state }), /обратитесь к администратору/);
|
||||
|
||||
const unlinked = await core.unlinkGoogle(db, egov.id);
|
||||
assert.equal(unlinked.googleSub, null);
|
||||
// Google-only account cannot drop its only way in.
|
||||
const [anna] = await db.select().from((await import("@peppa/db")).users).where((await import("drizzle-orm")).eq((await import("@peppa/db")).users.googleSub, "g-1001"));
|
||||
await assert.rejects(core.unlinkGoogle(db, anna!.id), /единственный/);
|
||||
google.account = { sub: "g-5005", email: "solo@example.com", email_verified: true };
|
||||
const so = await login();
|
||||
const solo = await core.completeGoogleFlow(db, { state: so.state, code: so.code, cookieState: so.f.state });
|
||||
await assert.rejects(core.unlinkGoogle(db, solo.user.id), /единственный/);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user