peppa/packages/core/src/superadmins.ts

36 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-226: a superadmin appoints and removes other superadmins from the web («Пользователи»).
import { m as tr } from "@peppa/shared/i18n";
import { projects, users, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { logEvent } from "./audit.ts";
import { PeppaError } from "./errors.ts";
import { isSuperadmin, setPlatformAdminId, superadminIds } from "./monitor.ts";
import { platformProjectKey } from "./platform-channel.ts";
import type { User } from "./users.ts";
/**
* Make `userId` a superadmin (`on`) or take it away. Only a superadmin may; nobody removes
* themself (so the last one cannot go either); a disabled account is not appointed. While
* `platform.admins` is unset (admins = the allowlist), the first change stores those accounts' ids.
*/
export async function setSuperadmin(db: Db, actor: Pick<User, "id" | "login">, userId: number, on: boolean): Promise<void> {
if (!(await isSuperadmin(db, actor))) throw new PeppaError(tr("Назначать суперадминов может только суперадмин."));
const [target] = await db.select().from(users).where(eq(users.id, userId));
if (!target) throw new PeppaError(tr("Не найдено"));
// PEP-294: the rights belong to the account (id), not to its login.
const admins = await superadminIds(db);
const has = admins.has(target.id);
if (on) {
if (has) return;
if (target.disabledAt) throw new PeppaError(tr("Сначала включите пользователя."));
await setPlatformAdminId(db, target.id, true);
} else {
if (!has) return;
if (target.id === actor.id) throw new PeppaError(tr("Нельзя снять права суперадмина с самого себя."));
if (admins.size <= 1) throw new PeppaError(tr("Нельзя снять последнего суперадмина."));
await setPlatformAdminId(db, target.id, false);
}
const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()));
if (platform) await logEvent(db, { projectId: platform.id, type: on ? "superadmin_added" : "superadmin_removed", payload: { login: target.login, by: actor.login } });
}