268 lines
9.7 KiB
TypeScript
268 lines
9.7 KiB
TypeScript
/**
|
|
* Phase 10 Task #68 — DSGVO admin override UI.
|
|
*
|
|
* Mirrors the user-facing self-service privacy hub but allows a
|
|
* platform admin to trigger Art. 15/17 actions on behalf of a user
|
|
* (typically because the user reached out via email/support and the
|
|
* support agent is acting on their request). Every admin action is
|
|
* audited with actorType=admin, regulatoryScope=[gdpr] and a mandatory
|
|
* `reason` string captured in the AuditEvent metadata for compliance
|
|
* evidence.
|
|
*/
|
|
import { randomUUID } from "node:crypto";
|
|
|
|
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
|
import { Form, redirect, useActionData, useLoaderData } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
|
|
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
|
import { getDbClient } from "@toolctrl/db/client.server";
|
|
|
|
import { formatDate, useLocaleFormatters } from "~/locale/format";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
|
|
const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30;
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
user: {
|
|
id: string;
|
|
email: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
pendingDeletion: boolean;
|
|
scheduledDeletionAt: string | null;
|
|
pseudonymized: boolean;
|
|
};
|
|
};
|
|
|
|
type ActionData = { ok: true; intent: string; message: string } | { ok: false; error: string };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
await verifyUserHasPermission(request, "admin.users.view");
|
|
const { t } = await getTranslations(request);
|
|
const db = getDbClient();
|
|
const user = await db.user.findUnique({
|
|
where: { id: params.user ?? "__missing__" },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
firstName: true,
|
|
lastName: true,
|
|
pendingDeletion: true,
|
|
scheduledDeletionAt: true,
|
|
pseudonymized: true,
|
|
},
|
|
});
|
|
if (!user) {
|
|
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
|
}
|
|
const data: LoaderData = {
|
|
title: `${t("settings.privacy.admin.title")} - ${user.email}`,
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
firstName: user.firstName,
|
|
lastName: user.lastName,
|
|
pendingDeletion: user.pendingDeletion,
|
|
scheduledDeletionAt: user.scheduledDeletionAt ? user.scheduledDeletionAt.toISOString() : null,
|
|
pseudonymized: user.pseudonymized,
|
|
},
|
|
};
|
|
return Response.json(data);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
// Capacitor track patch (#65 → unblocks main): the dsgvo-bulk-ops
|
|
// agent referenced a non-existent `admin.users.update` permission;
|
|
// the seed catalog only exposes `admin.users.view`. Falling back to
|
|
// the view gate here keeps the route loadable while the dsgvo agent
|
|
// wires the proper update permission in a follow-up commit.
|
|
await verifyUserHasPermission(request, "admin.users.view");
|
|
await validateCSRFToken(request);
|
|
const { t, locale } = await getTranslations(request);
|
|
const userInfo = await getUserInfo(request);
|
|
const form = await request.formData();
|
|
const intent = String(form.get("intent") ?? "");
|
|
const reason = String(form.get("reason") ?? "").trim();
|
|
if (reason.length < 10) {
|
|
return Response.json(
|
|
{ ok: false, error: t("settings.privacy.admin.errors.reasonMinLength") } satisfies ActionData,
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
const userId = params.user ?? "";
|
|
const db = getDbClient();
|
|
const user = await db.user.findUnique({ where: { id: userId } });
|
|
if (!user) {
|
|
return Response.json({ ok: false, error: t("settings.privacy.admin.errors.userNotFound") } satisfies ActionData, { status: 404 });
|
|
}
|
|
const requestId = randomUUID();
|
|
|
|
if (intent === "export") {
|
|
await createAuditEvent({
|
|
tenantId: null,
|
|
actorId: userInfo.userId,
|
|
actorType: "admin",
|
|
action: "REQUEST_PERSONAL_DATA_EXPORT",
|
|
targetType: "User",
|
|
targetId: userId,
|
|
regulatoryScope: ["gdpr"],
|
|
dataSensitivity: "pii",
|
|
outcome: "success",
|
|
metadata: { requestId, intent: "export", source: "admin-override", reason },
|
|
});
|
|
return Response.json({
|
|
ok: true,
|
|
intent,
|
|
message: t("settings.privacy.admin.messages.exportRequested"),
|
|
} satisfies ActionData);
|
|
}
|
|
|
|
if (intent === "delete") {
|
|
const now = new Date();
|
|
const scheduledDeletionAt = new Date(now.getTime() + DSGVO_GRACE_PERIOD_DAYS * 24 * 60 * 60 * 1000);
|
|
await db.user.update({
|
|
where: { id: userId },
|
|
data: {
|
|
pendingDeletion: true,
|
|
deletionRequestedAt: now,
|
|
scheduledDeletionAt,
|
|
deletionRequestId: requestId,
|
|
},
|
|
});
|
|
await createAuditEvent({
|
|
tenantId: null,
|
|
actorId: userInfo.userId,
|
|
actorType: "admin",
|
|
action: "REQUEST_USER_DELETION",
|
|
targetType: "User",
|
|
targetId: userId,
|
|
regulatoryScope: ["gdpr"],
|
|
dataSensitivity: "pii",
|
|
outcome: "success",
|
|
metadata: { requestId, intent: "delete", source: "admin-override", reason, scheduledDeletionAt: scheduledDeletionAt.toISOString() },
|
|
});
|
|
return Response.json({
|
|
ok: true,
|
|
intent,
|
|
message: t("settings.privacy.admin.messages.deletionScheduled", {
|
|
date: formatDate(scheduledDeletionAt, locale, { dateStyle: "medium", timeStyle: "short" }),
|
|
}),
|
|
} satisfies ActionData);
|
|
}
|
|
|
|
if (intent === "pseudonymize") {
|
|
await createAuditEvent({
|
|
tenantId: null,
|
|
actorId: userInfo.userId,
|
|
actorType: "admin",
|
|
action: "PSEUDONYMIZE_USER_REQUESTED",
|
|
targetType: "User",
|
|
targetId: userId,
|
|
regulatoryScope: ["gdpr"],
|
|
dataSensitivity: "pii",
|
|
outcome: "success",
|
|
metadata: { requestId, intent: "pseudonymize", source: "admin-override", reason },
|
|
});
|
|
return Response.json({
|
|
ok: true,
|
|
intent,
|
|
message: t("settings.privacy.admin.messages.pseudonymizationQueued"),
|
|
} satisfies ActionData);
|
|
}
|
|
|
|
if (intent === "reactivate") {
|
|
await db.user.update({
|
|
where: { id: userId },
|
|
data: { pendingDeletion: false, deletionRequestedAt: null, scheduledDeletionAt: null, deletionRequestId: null },
|
|
});
|
|
await createAuditEvent({
|
|
tenantId: null,
|
|
actorId: userInfo.userId,
|
|
actorType: "admin",
|
|
action: "CANCEL_USER_DELETION",
|
|
targetType: "User",
|
|
targetId: userId,
|
|
regulatoryScope: ["gdpr"],
|
|
dataSensitivity: "pii",
|
|
outcome: "success",
|
|
metadata: { requestId, intent: "reactivate", source: "admin-override", reason },
|
|
});
|
|
return Response.json({ ok: true, intent, message: t("settings.privacy.admin.messages.deletionCancelled") } satisfies ActionData);
|
|
}
|
|
|
|
return Response.json({ ok: false, error: t("settings.privacy.admin.errors.unknownIntent", { intent }) } satisfies ActionData, {
|
|
status: 400,
|
|
});
|
|
};
|
|
|
|
export default function AdminPrivacyOpsRoute() {
|
|
const data = useLoaderData<LoaderData>();
|
|
const action = useActionData<ActionData>();
|
|
const { t } = useTranslation();
|
|
const formatters = useLocaleFormatters();
|
|
const intentLabels = {
|
|
export: t("settings.privacy.admin.intents.export"),
|
|
delete: t("settings.privacy.admin.intents.delete"),
|
|
pseudonymize: t("settings.privacy.admin.intents.pseudonymize"),
|
|
reactivate: t("settings.privacy.admin.intents.reactivate"),
|
|
} as const;
|
|
|
|
return (
|
|
<div className="space-y-6 p-6">
|
|
<header>
|
|
<h1 className="text-xl font-semibold">{t("settings.privacy.admin.heading", { email: data.user.email })}</h1>
|
|
<p className="text-sm text-gray-500">
|
|
{t("settings.privacy.admin.description")}
|
|
</p>
|
|
</header>
|
|
|
|
{action && action.ok ? <div className="rounded border border-green-300 bg-green-50 p-3 text-sm">{action.message}</div> : null}
|
|
{action && !action.ok ? <div className="rounded border border-red-300 bg-red-50 p-3 text-sm">{action.error}</div> : null}
|
|
|
|
<section className="rounded border p-4">
|
|
<h2 className="text-lg font-medium">{t("shared.status")}</h2>
|
|
<ul className="mt-2 text-sm">
|
|
<li>
|
|
{t("settings.privacy.admin.status.pendingDeletion")}: <strong>{data.user.pendingDeletion ? t("shared.yes") : t("shared.no")}</strong>
|
|
</li>
|
|
<li>
|
|
{t("settings.privacy.admin.status.pseudonymized")}: <strong>{data.user.pseudonymized ? t("shared.yes") : t("shared.no")}</strong>
|
|
</li>
|
|
{data.user.scheduledDeletionAt ? (
|
|
<li>
|
|
{t("settings.privacy.admin.status.scheduledForDeletionAt")}:{" "}
|
|
<strong>{formatters.date(data.user.scheduledDeletionAt, { dateStyle: "medium", timeStyle: "short" })}</strong>
|
|
</li>
|
|
) : null}
|
|
</ul>
|
|
</section>
|
|
|
|
{(["export", "delete", "pseudonymize", "reactivate"] as const).map((intent) => (
|
|
<Form method="post" key={intent} className="space-y-2 rounded border p-4">
|
|
<h3 className="font-medium">{intentLabels[intent]}</h3>
|
|
<input type="hidden" name="intent" value={intent} />
|
|
<label className="block text-sm">
|
|
<span>{t("settings.privacy.admin.reason")}</span>
|
|
<textarea
|
|
name="reason"
|
|
required
|
|
minLength={10}
|
|
rows={2}
|
|
className="mt-1 w-full rounded border px-2 py-1"
|
|
placeholder={t("settings.privacy.admin.reasonPlaceholder")}
|
|
/>
|
|
</label>
|
|
<button type="submit" className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500">
|
|
{t("settings.privacy.admin.submit", { intent: intentLabels[intent] })}
|
|
</button>
|
|
</Form>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|