76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
"use server";
|
|
// «Хосты» (PEP-40): every action is superadmin-only (others get "not found").
|
|
|
|
import { createHost, deleteHost, getHost, PeppaError, requireSuperadmin, setHostDisabled, updateHost } from "@peppa/core";
|
|
import { checkHost, ensureSshKey } from "@peppa/runner";
|
|
import { revalidatePath } from "next/cache";
|
|
import { redirect } from "next/navigation";
|
|
import { asWebActor, requireUser } from "@/lib/auth";
|
|
import { db } from "@/lib/db";
|
|
import { getT } from "@/lib/i18n";
|
|
|
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
|
const BASE = "/hosts";
|
|
|
|
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
|
const user = asWebActor(await requireUser());
|
|
let target = BASE;
|
|
try {
|
|
await requireSuperadmin(db, user);
|
|
target = (await fn()) || target;
|
|
} catch (e) {
|
|
const t = await getT();
|
|
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
|
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
|
}
|
|
revalidatePath("/", "layout");
|
|
redirect(target);
|
|
}
|
|
|
|
const fields = (f: FormData) => ({
|
|
sshTarget: str(f, "sshTarget"),
|
|
sshPort: str(f, "sshPort") ? Number(str(f, "sshPort")) : undefined,
|
|
workdir: str(f, "workdir") || undefined,
|
|
peppaUrl: str(f, "peppaUrl") || null,
|
|
});
|
|
|
|
export async function addHostAction(f: FormData) {
|
|
await attempt(f, async () => {
|
|
await ensureSshKey();
|
|
const h = await createHost(db, { name: str(f, "name"), ...fields(f) });
|
|
await checkHost(db, h);
|
|
return `${BASE}#h-${h.id}`;
|
|
});
|
|
}
|
|
|
|
export async function updateHostAction(f: FormData) {
|
|
await attempt(f, async () => {
|
|
const id = Number(str(f, "id"));
|
|
const h = await updateHost(db, id, fields(f));
|
|
await checkHost(db, h);
|
|
return `${BASE}#h-${id}`;
|
|
});
|
|
}
|
|
|
|
export async function checkHostAction(f: FormData) {
|
|
await attempt(f, async () => {
|
|
const id = Number(str(f, "id"));
|
|
await checkHost(db, await getHost(db, id));
|
|
return `${BASE}#h-${id}`;
|
|
});
|
|
}
|
|
|
|
export async function toggleHostAction(f: FormData) {
|
|
await attempt(f, async () => {
|
|
const id = Number(str(f, "id"));
|
|
await setHostDisabled(db, id, str(f, "disable") === "1");
|
|
return `${BASE}#h-${id}`;
|
|
});
|
|
}
|
|
|
|
export async function deleteHostAction(f: FormData) {
|
|
await attempt(f, async () => {
|
|
await deleteHost(db, Number(str(f, "id")));
|
|
});
|
|
}
|