Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { UserWithDetails, getUserByEmail, getUserByEmailWithDetails } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
user: UserWithDetails;
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const user = await getUserByEmailWithDetails(params.user!);
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
user,
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const user = await getUserByEmail(params.user);
|
||||
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "set-user-roles") {
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
let setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
setRoles = setRoles.filter((v, i, a) => a.findIndex((t) => t.role.id === v.role.id) === i);
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const countAdmins = await db.adminUser.count();
|
||||
if (!isAdmin && countAdmins === 1) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveLastAdmin") }, { status: 400 });
|
||||
}
|
||||
const hasSuperAdmin = setRoles.some((r) => r.role.name === DefaultAdminRoles.SuperAdmin);
|
||||
if (user.id === userInfo.userId && !hasSuperAdmin) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveOwnSuperAdmin") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
// return Response.json({ success: t("shared.updated") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>(data.user.roles?.filter((f) => f.role.type === "admin").map((r) => r.role.id));
|
||||
|
||||
function hasSomeAdminRoles() {
|
||||
return data.adminRoles.some((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
function hasAllAdminRoles() {
|
||||
return data.adminRoles.every((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="set-user-roles" hidden readOnly />
|
||||
{selectedRoles?.map((role, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="border-border flex items-center justify-between space-x-2 border-b pb-2">
|
||||
<div className="text-foreground/80 text-lg font-medium">{t("models.role.plural")}</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary disabled={!hasSomeAdminRoles()} onClick={() => setSelectedRoles([])}>
|
||||
{t("shared.clear")}
|
||||
</ButtonSecondary>
|
||||
|
||||
<ButtonSecondary disabled={hasAllAdminRoles()} onClick={() => setSelectedRoles(data.adminRoles.map((r) => r.id))}>
|
||||
{t("shared.selectAll")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-1 rounded-md shadow-2xs">
|
||||
{data.adminRoles?.map((role, idx) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={idx}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
<ActionResultModal actionData={actionData ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const data: LoaderData = {
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "new-user") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const email = form.get("email")?.toString();
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!email || !password || !firstName) {
|
||||
return Response.json({ error: t("admin.users.create.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
// if (arrRoles.length === 0) {
|
||||
// return Response.json({ error: "You must select at least one role." }, { status: 400 });
|
||||
// }
|
||||
|
||||
const existingUser = await getUserByEmail(email);
|
||||
if (existingUser) {
|
||||
return Response.json({ error: t("admin.users.create.errors.userAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
const setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const { id } = await register({
|
||||
email,
|
||||
firstName,
|
||||
lastName: lastName ?? "",
|
||||
password,
|
||||
request,
|
||||
});
|
||||
const user = await getUser(id);
|
||||
if (!user) {
|
||||
return Response.json({ error: t("admin.users.create.errors.unexpectedCreateError") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [password, setPassword] = useState<string>("");
|
||||
const [firstName, setFirstName] = useState<string>("");
|
||||
const [lastName, setLastName] = useState<string>("");
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="new-user" hidden readOnly />
|
||||
{selectedRoles?.map((role) => {
|
||||
return (
|
||||
<input
|
||||
key={role}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText autoFocus type="email" name="email" title={t("models.user.email")} value={email} setValue={setEmail} required />
|
||||
|
||||
<InputText type="password" name="password" title={t("account.shared.password")} value={password} setValue={setPassword} required />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} value={firstName} setValue={setFirstName} required />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} value={lastName} setValue={setLastName} />
|
||||
|
||||
<div>
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">{t("models.role.plural")}</label>
|
||||
<div className="border-border bg-background divide-border divide-y rounded-md border px-2 py-1">
|
||||
{data.adminRoles?.map((role) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={role.name}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user