126 lines
5.4 KiB
TypeScript
126 lines
5.4 KiB
TypeScript
// Tenant-wide organisation password-manager ADMIN view. Lists ALL
|
|
// vaults in the tenant with entry/access counts for management (archive, access
|
|
// oversight) but NEVER grants content access — secret values are unreachable from
|
|
// here without a per-vault access row. Gated by hr.passwordsafe.admin.
|
|
//
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData, useSubmit } from "react-router";
|
|
import { buildAdminVaultListVM, type AdminVaultRow as AdminVaultVMRow, type AdminVaultListVM } from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
|
|
import { adminListAllVaults, archiveVault, listPasswordSafeActivity, restoreVault } from "~/utils/integrations/hrPasswordSafeService.server";
|
|
import { passwordSafeVaultPath } from "~/utils/integrations/passwordSafeRoutePaths";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { HrAdminPasswordSafePage } from "~/components/screens/hr/HrAdminPasswordSafePage";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
|
|
type LoaderData = { title: string; vm: AdminVaultListVM };
|
|
type PasswordSafeActionData = { ok?: boolean; messageKey?: string; error?: string };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t, locale } = await getTranslations(request);
|
|
const ctx = await loadHrContext({ request, params });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const searchQuery = new URL(request.url).searchParams.get("q")?.trim().slice(0, 100) ?? "";
|
|
|
|
if (!ctx.hasModule) {
|
|
throw notFoundResponse();
|
|
}
|
|
try {
|
|
requireHrPermission(ctx, "hr.passwordsafe.admin");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
|
|
const [vaults, activities] = await Promise.all([
|
|
adminListAllVaults(ctx.tenantId, { includeArchived: true, userId: ctx.userId, search: searchQuery }),
|
|
listPasswordSafeActivity({ tenantId: ctx.tenantId, userId: ctx.userId, isTenantPasswordSafeAdmin: true }),
|
|
]);
|
|
const rows: AdminVaultVMRow[] = vaults.map((vault) => ({
|
|
id: vault.id,
|
|
name: vault.name,
|
|
entryCount: vault.entryCount,
|
|
accessCount: vault.accessCount,
|
|
archived: vault.archivedAt != null,
|
|
detailHref: vault.hasContentAccess ? passwordSafeVaultPath(tenantSlug, vault.id) : null,
|
|
}));
|
|
|
|
return Response.json({
|
|
title: `${t("hr.admin.passwordSafe.title")} | ${process.env.APP_NAME}`,
|
|
vm: buildAdminVaultListVM({
|
|
rows,
|
|
searchQuery,
|
|
activityRows: activities.map((activity) => ({
|
|
id: activity.id,
|
|
createdAtLabel: new Intl.DateTimeFormat(locale, { dateStyle: "short", timeStyle: "short" }).format(activity.createdAt),
|
|
actionLabelKey: `hr.passwordSafe.activity.${activity.action.replace("HR_PASSWORD_SAFE_", "").toLowerCase()}`,
|
|
actorLabel: activity.actorLabel,
|
|
successful: activity.outcome === "success",
|
|
})),
|
|
}),
|
|
} satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadHrContext({ request, params, requireModule: true });
|
|
requireHrPermission(ctx, "hr.passwordsafe.admin");
|
|
const form = await request.formData();
|
|
await validateCSRFToken(request, { formData: form });
|
|
const intent = form.get("intent")?.toString();
|
|
|
|
try {
|
|
if (intent === "archive-vault") {
|
|
await archiveVault({ tenantId: ctx.tenantId, vaultId: form.get("vaultId")?.toString() ?? "", userId: ctx.userId, isTenantPasswordSafeAdmin: true });
|
|
return Response.json({ ok: true, messageKey: "hr.passwordSafe.feedback.vaultArchived" });
|
|
}
|
|
if (intent === "restore-vault") {
|
|
await restoreVault({ tenantId: ctx.tenantId, vaultId: form.get("vaultId")?.toString() ?? "", userId: ctx.userId, isTenantPasswordSafeAdmin: true });
|
|
return Response.json({ ok: true, messageKey: "hr.passwordSafe.feedback.vaultRestored" });
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof Response) {
|
|
throw error;
|
|
}
|
|
return hrActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function HrAdminPasswordSafeRoute() {
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher<PasswordSafeActionData>();
|
|
// The action answers with `{ ok, messageKey }` or an error key, so the
|
|
// confirmation follows the server's verdict. It replaces the inline alert
|
|
// this screen used to render — one save, one message.
|
|
useSaveToast(fetcher.data);
|
|
const submit = useSubmit();
|
|
const { csrf } = useRootData();
|
|
function mutate(intent: string, vaultId: string) {
|
|
const body = new FormData();
|
|
body.set("intent", intent);
|
|
body.set("vaultId", vaultId);
|
|
if (csrf) body.set("csrf", csrf);
|
|
fetcher.submit(body, { method: "post" });
|
|
}
|
|
return (
|
|
<HrAdminPasswordSafePage
|
|
vm={vm}
|
|
submitting={fetcher.state !== "idle"}
|
|
actions={{
|
|
onArchiveVault: (vaultId) => mutate("archive-vault", vaultId),
|
|
onRestoreVault: (vaultId) => mutate("restore-vault", vaultId),
|
|
onSearch: (query) => {
|
|
const body = new FormData();
|
|
if (query.trim()) body.set("q", query.trim());
|
|
void submit(body, { method: "get" });
|
|
},
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|