peppa/packages/core/src/superadmins.ts

37 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, platformAdmins, setPlatformAdmins } 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 that list explicitly.
*/
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("Не найдено"));
const login = target.login.toLowerCase();
const admins = await platformAdmins(db);
const has = admins.includes(login);
if (on) {
if (has) return;
if (target.disabledAt) throw new PeppaError(tr("Сначала включите пользователя."));
await setPlatformAdmins(db, [...admins, login]);
} else {
if (!has) return;
if (target.id === actor.id) throw new PeppaError(tr("Нельзя снять права суперадмина с самого себя."));
const rest = admins.filter((l) => l !== login);
if (!rest.length) throw new PeppaError(tr("Нельзя снять последнего суперадмина."));
await setPlatformAdmins(db, rest);
}
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 } });
}