Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+90
@@ -0,0 +1,90 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantUsers } from "~/utils/db/users.db.server";
|
||||
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantConnectorRows } from "~/services/admin/subscription-assembly.server";
|
||||
import { getTenantNoteRows } from "~/services/admin/tenant-notes.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { loader } from "./$id";
|
||||
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/services/admin/subscription-assembly.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/subscription-assembly.server")>("~/services/admin/subscription-assembly.server");
|
||||
return { ...actual, getTenantConnectorRows: vi.fn(), setTenantFeatureConnector: vi.fn() };
|
||||
});
|
||||
vi.mock("~/services/admin/tenant-notes.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/tenant-notes.server")>("~/services/admin/tenant-notes.server");
|
||||
return { ...actual, getTenantNoteRows: vi.fn(), createTenantNote: vi.fn(), deleteTenantNote: vi.fn() };
|
||||
});
|
||||
vi.mock("~/utils/db.server", () => ({ db: { tenantSubscription: { findUnique: vi.fn() } } }));
|
||||
vi.mock("~/utils/db/tenants.db.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/utils/db/tenants.db.server")>("~/utils/db/tenants.db.server");
|
||||
return { ...actual, getTenant: vi.fn() };
|
||||
});
|
||||
vi.mock("~/utils/db/users.db.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/utils/db/users.db.server")>("~/utils/db/users.db.server");
|
||||
return { ...actual, adminGetAllTenantUsers: vi.fn() };
|
||||
});
|
||||
vi.mock("~/utils/db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn() }));
|
||||
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({ getAllSubscriptionProducts: vi.fn() }));
|
||||
|
||||
describe("admin account tenant RLS context", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(getTenant).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return {
|
||||
id: "tenant_1",
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
users: [],
|
||||
} as never;
|
||||
});
|
||||
vi.mocked(adminGetAllTenantUsers).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return [];
|
||||
});
|
||||
vi.mocked(getTenantSubscription).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return null;
|
||||
});
|
||||
vi.mocked(getAllSubscriptionProducts).mockResolvedValue([]);
|
||||
vi.mocked(getTenantConnectorRows).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return [];
|
||||
});
|
||||
vi.mocked(getTenantNoteRows).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return [];
|
||||
});
|
||||
vi.mocked(db.tenantSubscription.findUnique).mockImplementation((async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return null;
|
||||
}) as never);
|
||||
});
|
||||
|
||||
it("binds the target tenant only after the admin permission check", async () => {
|
||||
const data = await loader({
|
||||
request: new Request("https://admin.example.test/accounts/tenant_1"),
|
||||
params: { id: "tenant_1" },
|
||||
context: {},
|
||||
} as LoaderFunctionArgs);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getTenant).mock.invocationCallOrder[0]);
|
||||
expect(data.tenant.id).toBe("tenant_1");
|
||||
});
|
||||
});
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import {
|
||||
forgetTenantTrustedDevice,
|
||||
getTenantSecuritySnapshot,
|
||||
revokeTenantUserSession,
|
||||
TenantSecurityError,
|
||||
} from "~/services/admin/tenant-security.server";
|
||||
import { action, loader } from "./$id.security";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/locale/format", () => ({
|
||||
useLocaleFormatters: () => ({
|
||||
dateTime: (value: string) => value,
|
||||
}),
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/services/admin/tenant-security.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/tenant-security.server")>("~/services/admin/tenant-security.server");
|
||||
return {
|
||||
...actual,
|
||||
getTenantSecuritySnapshot: vi.fn(),
|
||||
revokeTenantUserSession: vi.fn(),
|
||||
forgetTenantTrustedDevice: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function callLoader(id = "tenant_1") {
|
||||
return loader({ request: new Request("https://admin.example.test/accounts/tenant_1/security"), params: { id }, context: {} } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
function callAction(form: Record<string, string>, id = "tenant_1") {
|
||||
return action({
|
||||
request: new Request("https://admin.example.test/accounts/tenant_1/security", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams(form),
|
||||
}),
|
||||
params: { id },
|
||||
context: {},
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant security route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "admin_1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "admin_1", email: "admin@hivegrid.de" } as never);
|
||||
vi.mocked(getTenantSecuritySnapshot).mockResolvedValue({
|
||||
now: "2026-07-09T10:00:00.000Z",
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
||||
users: [
|
||||
{
|
||||
id: "user_1",
|
||||
email: "owner@example.test",
|
||||
name: "Owner Example",
|
||||
active: true,
|
||||
membershipStatus: "active",
|
||||
mfaEnabled: true,
|
||||
mfaPending: false,
|
||||
recoveryCodesConfigured: true,
|
||||
},
|
||||
],
|
||||
sessions: [],
|
||||
trustedDevices: [],
|
||||
magicLinks: [],
|
||||
ipLogs: [],
|
||||
auditEvents: [],
|
||||
});
|
||||
vi.mocked(revokeTenantUserSession).mockResolvedValue(undefined);
|
||||
vi.mocked(forgetTenantTrustedDevice).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("checks the tenant view permission and builds the security VM", async () => {
|
||||
vi.mocked(getTenantSecuritySnapshot).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return {
|
||||
now: "2026-07-09T10:00:00.000Z",
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
||||
users: [
|
||||
{
|
||||
id: "user_1",
|
||||
email: "owner@example.test",
|
||||
name: "Owner Example",
|
||||
active: true,
|
||||
membershipStatus: "active",
|
||||
mfaEnabled: true,
|
||||
mfaPending: false,
|
||||
recoveryCodesConfigured: true,
|
||||
},
|
||||
],
|
||||
sessions: [],
|
||||
trustedDevices: [],
|
||||
magicLinks: [],
|
||||
ipLogs: [],
|
||||
auditEvents: [],
|
||||
};
|
||||
});
|
||||
const data = await callLoader();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.view");
|
||||
expect(getTenantSecuritySnapshot).toHaveBeenCalledWith("tenant_1");
|
||||
expect(data.vm.status).toBe("ready");
|
||||
});
|
||||
|
||||
it("redirects to account list when the tenant is missing", async () => {
|
||||
vi.mocked(getTenantSecuritySnapshot).mockRejectedValueOnce(new TenantSecurityError("TENANT_NOT_FOUND"));
|
||||
|
||||
await expect(callLoader("missing")).rejects.toMatchObject({ status: 302 });
|
||||
});
|
||||
|
||||
it("revokes a user session through the audited service", async () => {
|
||||
vi.mocked(revokeTenantUserSession).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
});
|
||||
const response = (await callAction({
|
||||
csrf: "csrf",
|
||||
action: "revoke-session",
|
||||
sessionId: "session_1",
|
||||
reason: "Supportfall MFA Reset",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.tenantSecurity.actions.sessionRevoked" });
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.settings.update");
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(revokeTenantUserSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
sessionId: "session_1",
|
||||
reason: "Supportfall MFA Reset",
|
||||
actorUserId: "admin_1",
|
||||
actorEmail: "admin@hivegrid.de",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("forgets a trusted device through the audited service", async () => {
|
||||
vi.mocked(forgetTenantTrustedDevice).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
});
|
||||
const response = (await callAction({
|
||||
csrf: "csrf",
|
||||
action: "forget-device",
|
||||
trustedDeviceId: "device_1",
|
||||
reason: "Geraet verloren",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.tenantSecurity.actions.deviceForgotten" });
|
||||
expect(forgetTenantTrustedDevice).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", trustedDeviceId: "device_1" }));
|
||||
});
|
||||
});
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
import {
|
||||
buildTenantSecurityVM,
|
||||
type TenantSecurityMetric,
|
||||
type TenantSecurityData,
|
||||
type TenantSecurityRisk,
|
||||
type TenantSecuritySessionRow,
|
||||
type TenantSecurityTone,
|
||||
type TenantSecurityTrustedDeviceRow,
|
||||
} from "@hivegrid/view-models";
|
||||
import { AlertTriangle, ArrowLeft, KeyRound, LinkIcon, MonitorSmartphone, ShieldCheck, ShieldX, UserRoundCheck } from "lucide-react";
|
||||
import type React from "react";
|
||||
import { Form, Link, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData, useNavigation, type ActionFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import {
|
||||
forgetTenantTrustedDevice,
|
||||
getTenantSecuritySnapshot,
|
||||
revokeTenantUserSession,
|
||||
TenantSecurityError,
|
||||
} from "~/services/admin/tenant-security.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildTenantSecurityVM>;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = params.id;
|
||||
if (!tenantId) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
try {
|
||||
const snapshot = await runWithRlsContext({ tenantId }, () => getTenantSecuritySnapshot(tenantId));
|
||||
return {
|
||||
title: `${t("admin.tenantSecurity.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildTenantSecurityVM(snapshot),
|
||||
} satisfies LoaderData;
|
||||
} catch (error) {
|
||||
if (error instanceof TenantSecurityError && error.code === "TENANT_NOT_FOUND") {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const reason = form.get("reason")?.toString() ?? "";
|
||||
const tenantId = params.id ?? "";
|
||||
|
||||
try {
|
||||
if (action === "revoke-session") {
|
||||
await runWithRlsContext({ tenantId }, () =>
|
||||
revokeTenantUserSession({
|
||||
tenantId,
|
||||
sessionId: form.get("sessionId")?.toString() ?? "",
|
||||
reason,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
})
|
||||
);
|
||||
return Response.json({ success: t("admin.tenantSecurity.actions.sessionRevoked") } satisfies ActionData);
|
||||
}
|
||||
if (action === "forget-device") {
|
||||
await runWithRlsContext({ tenantId }, () =>
|
||||
forgetTenantTrustedDevice({
|
||||
tenantId,
|
||||
trustedDeviceId: form.get("trustedDeviceId")?.toString() ?? "",
|
||||
reason,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
})
|
||||
);
|
||||
return Response.json({ success: t("admin.tenantSecurity.actions.deviceForgotten") } satisfies ActionData);
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
} catch (error) {
|
||||
if (error && typeof error === "object" && "i18nKey" in error && typeof error.i18nKey === "string") {
|
||||
return badRequest({ error: t(error.i18nKey) });
|
||||
}
|
||||
if (error instanceof TenantSecurityError) {
|
||||
return badRequest({ error: t(`admin.tenantSecurity.errors.${error.code}`) });
|
||||
}
|
||||
return badRequest({ error: t("admin.tenantSecurity.errors.actionFailed") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function TenantSecurityRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const loading = navigation.state === "submitting";
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.tenantSecurity.title")} fullWidth>
|
||||
{data.vm.status === "ready" ? (
|
||||
<TenantSecurityPage data={data.vm.data} actionData={actionData} loading={loading} />
|
||||
) : (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.tenantSecurity.empty.title")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.tenantSecurity.empty.body")}</div>
|
||||
</div>
|
||||
)}
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function TenantSecurityPage({
|
||||
data,
|
||||
actionData,
|
||||
loading,
|
||||
}: {
|
||||
data: TenantSecurityData;
|
||||
actionData: ActionData | undefined;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="min-w-0">
|
||||
<Link to={adminPath(`accounts/${data.tenant.id}`, { mode: "host-aware" })} className="text-primary inline-flex items-center gap-1 text-sm font-medium hover:underline">
|
||||
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||
{t("admin.tenantSecurity.backToTenant")}
|
||||
</Link>
|
||||
<div className="text-muted-foreground mt-2 text-sm">
|
||||
{t("admin.tenantSecurity.description", { tenant: data.tenant.name, slug: data.tenant.slug })}
|
||||
</div>
|
||||
</div>
|
||||
<Badge color={riskBadgeColor(data.risk)} withColorDot>
|
||||
{t(data.riskLabelKey)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-3 text-sm">{t(data.riskDetailKey)}</div>
|
||||
{actionData?.success ? <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div> : null}
|
||||
{actionData?.error ? <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div> : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
|
||||
{data.metrics.map((metric) => (
|
||||
<MetricCard key={metric.id} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{data.issues.length > 0 ? (
|
||||
<Card className="gap-4 rounded-lg border-yellow-200 bg-yellow-50 py-5">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base text-yellow-950">
|
||||
<AlertTriangle className="size-5" aria-hidden="true" />
|
||||
{t("admin.tenantSecurity.issues.title")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="grid gap-2 text-sm text-yellow-900 md:grid-cols-2">
|
||||
{data.issues.map((issue) => (
|
||||
<li key={issue}>{t(issue)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.users.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.users.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[760px] text-sm">
|
||||
<thead className="text-muted-foreground border-b text-left">
|
||||
<tr>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.user")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.status")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.mfa")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.recovery")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.risk")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{data.users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="font-medium">{user.name}</div>
|
||||
<div className="text-muted-foreground">{user.email}</div>
|
||||
</td>
|
||||
<td className="py-3 pr-4">{t(user.statusLabelKey)}</td>
|
||||
<td className="py-3 pr-4">{t(user.mfaLabelKey)}</td>
|
||||
<td className="py-3 pr-4">{user.recoveryCodesConfigured ? t("shared.yes") : t("shared.no")}</td>
|
||||
<td className="py-3 pr-4">
|
||||
<Badge color={riskBadgeColor(user.risk)} withColorDot>
|
||||
{t(user.riskLabelKey)}
|
||||
</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<SessionsCard rows={data.sessions} loading={loading} />
|
||||
<TrustedDevicesCard rows={data.trustedDevices} loading={loading} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.magicLinks.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.magicLinks.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompactRows
|
||||
emptyKey="admin.tenantSecurity.magicLinks.empty"
|
||||
rows={data.magicLinks.map((link) => ({
|
||||
id: link.id,
|
||||
title: link.userEmail,
|
||||
detail: `${t(link.statusLabelKey)} · ${link.expiresAt}`,
|
||||
tone: link.tone,
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.ipLogs.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.ipLogs.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompactRows
|
||||
emptyKey="admin.tenantSecurity.ipLogs.empty"
|
||||
rows={data.ipLogs.map((log) => ({
|
||||
id: log.id,
|
||||
title: `${log.maskedIp} · ${log.actorLabel}`,
|
||||
detail: `${log.fromUrl} · ${log.createdAt}`,
|
||||
tone: "neutral",
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.audit.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.audit.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompactRows
|
||||
emptyKey="admin.tenantSecurity.audit.empty"
|
||||
rows={data.auditEvents.map((event) => ({
|
||||
id: event.id,
|
||||
title: event.displaySummary,
|
||||
detail: `${event.actorEmail ?? event.actorId ?? "system"} · ${event.createdAt}`,
|
||||
tone: event.tone,
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ metric }: { metric: TenantSecurityMetric }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<CardTitle className="text-sm leading-5">{t(metric.labelKey)}</CardTitle>
|
||||
<CardDescription className="mt-1 leading-5">{t(metric.detailKey)}</CardDescription>
|
||||
</div>
|
||||
<div className={`flex size-10 shrink-0 items-center justify-center rounded-md border ${toneIconClasses(metric.tone)}`}>{metricIcon(metric.id)}</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold leading-7">{metric.value}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionsCard({ rows, loading }: { rows: readonly TenantSecuritySessionRow[]; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.sessions.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.sessions.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{rows.length === 0 ? <div className="text-muted-foreground text-sm">{t("admin.tenantSecurity.sessions.empty")}</div> : null}
|
||||
{rows.map((session) => (
|
||||
<div key={session.id} className="rounded-md border p-3">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="font-medium">{session.displayDevice}</div>
|
||||
<Badge color={toneBadgeColor(session.tone)} withColorDot>
|
||||
{t(session.statusLabelKey)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{session.userEmail}</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs">
|
||||
{t("admin.tenantSecurity.sessions.lastSeen", { value: format.dateTime(session.lastSeenAt) })}
|
||||
</div>
|
||||
</div>
|
||||
{session.status === "active" || session.status === "trusted" ? (
|
||||
<SecurityActionForm action="revoke-session" idName="sessionId" idValue={session.id} buttonKey="admin.tenantSecurity.actions.revokeSession" loading={loading} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TrustedDevicesCard({ rows, loading }: { rows: readonly TenantSecurityTrustedDeviceRow[]; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.devices.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.devices.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{rows.length === 0 ? <div className="text-muted-foreground text-sm">{t("admin.tenantSecurity.devices.empty")}</div> : null}
|
||||
{rows.map((device) => (
|
||||
<div key={device.id} className="rounded-md border p-3">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="font-medium">{device.displayDevice}</div>
|
||||
<Badge color={toneBadgeColor(device.tone)} withColorDot>
|
||||
{t(device.statusLabelKey)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{device.userEmail}</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs">
|
||||
{t("admin.tenantSecurity.devices.lastUsed", { value: format.dateTime(device.lastUsedAt) })}
|
||||
</div>
|
||||
</div>
|
||||
{device.status === "active" ? (
|
||||
<SecurityActionForm action="forget-device" idName="trustedDeviceId" idValue={device.id} buttonKey="admin.tenantSecurity.actions.forgetDevice" loading={loading} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SecurityActionForm({
|
||||
action,
|
||||
idName,
|
||||
idValue,
|
||||
buttonKey,
|
||||
loading,
|
||||
}: {
|
||||
action: string;
|
||||
idName: string;
|
||||
idValue: string;
|
||||
buttonKey: string;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
return (
|
||||
<Form method="post" className="flex w-full flex-col gap-2 md:w-72">
|
||||
<input type="hidden" name="action" value={action} />
|
||||
<input type="hidden" name={idName} value={idValue} />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} />
|
||||
<input
|
||||
name="reason"
|
||||
required
|
||||
minLength={5}
|
||||
placeholder={t("admin.tenantSecurity.actions.reasonPlaceholder")}
|
||||
className="border-border bg-background h-9 rounded-md border px-3 text-sm focus-visible:outline-none focus-visible:shadow-focus"
|
||||
/>
|
||||
<ButtonSecondary disabled={loading} type="submit">
|
||||
{t(buttonKey)}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function CompactRows({
|
||||
rows,
|
||||
emptyKey,
|
||||
}: {
|
||||
rows: readonly { readonly id: string; readonly title: string; readonly detail: string; readonly tone: TenantSecurityTone }[];
|
||||
emptyKey: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (rows.length === 0) return <div className="text-muted-foreground text-sm">{t(emptyKey)}</div>;
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{rows.map((row) => (
|
||||
<div key={row.id} className="flex items-start justify-between gap-3 rounded-md border p-3 text-sm">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">{row.title}</div>
|
||||
<div className="text-muted-foreground mt-1 truncate">{row.detail}</div>
|
||||
</div>
|
||||
<span className={`mt-1 size-2 shrink-0 rounded-full ${toneDotClass(row.tone)}`} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function metricIcon(id: string): React.ReactNode {
|
||||
if (id === "mfa") return <ShieldCheck className="size-5" aria-hidden="true" />;
|
||||
if (id === "sessions") return <MonitorSmartphone className="size-5" aria-hidden="true" />;
|
||||
if (id === "devices") return <KeyRound className="size-5" aria-hidden="true" />;
|
||||
if (id === "magicLinks") return <LinkIcon className="size-5" aria-hidden="true" />;
|
||||
if (id === "loginFailures") return <ShieldX className="size-5" aria-hidden="true" />;
|
||||
return <UserRoundCheck className="size-5" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function riskBadgeColor(risk: TenantSecurityRisk): BadgeColor {
|
||||
if (risk === "high") return "red";
|
||||
if (risk === "medium") return "yellow";
|
||||
return "green";
|
||||
}
|
||||
|
||||
function toneBadgeColor(tone: TenantSecurityTone): BadgeColor {
|
||||
if (tone === "danger") return "red";
|
||||
if (tone === "warning") return "yellow";
|
||||
if (tone === "success") return "green";
|
||||
return "gray";
|
||||
}
|
||||
|
||||
function toneIconClasses(tone: TenantSecurityTone): string {
|
||||
if (tone === "danger") return "border-red-200 bg-red-50 text-red-700";
|
||||
if (tone === "warning") return "border-yellow-200 bg-yellow-50 text-yellow-700";
|
||||
if (tone === "success") return "border-green-200 bg-green-50 text-green-700";
|
||||
return "border-border bg-surface-neutral-primary text-muted-foreground";
|
||||
}
|
||||
|
||||
function toneDotClass(tone: TenantSecurityTone): string {
|
||||
if (tone === "danger") return "bg-red-500";
|
||||
if (tone === "warning") return "bg-yellow-500";
|
||||
if (tone === "success") return "bg-green-500";
|
||||
return "bg-gray-300";
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { buildTenantSupportSummary } from "./$id";
|
||||
|
||||
describe("admin tenant support console", () => {
|
||||
it("builds tenant-specific support metrics and deep links", () => {
|
||||
const summary = buildTenantSupportSummary({
|
||||
tenant: {
|
||||
id: "tenant_1",
|
||||
slug: "acme",
|
||||
name: "Acme",
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
users: [
|
||||
{
|
||||
type: TenantUserType.OWNER,
|
||||
user: { email: "owner@example.test" },
|
||||
},
|
||||
],
|
||||
} as never,
|
||||
users: [
|
||||
{
|
||||
email: "owner@example.test",
|
||||
tenants: [{ tenantId: "tenant_1", status: TenantUserStatus.ACTIVE }],
|
||||
},
|
||||
{
|
||||
email: "inactive@example.test",
|
||||
tenants: [{ tenantId: "tenant_1", status: TenantUserStatus.INACTIVE }],
|
||||
},
|
||||
] as never,
|
||||
subscription: {
|
||||
status: "past_due",
|
||||
planCode: "business",
|
||||
seatQuantity: 7,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: null,
|
||||
pastDueSince: new Date("2026-07-01T00:00:00.000Z"),
|
||||
frozenAt: null,
|
||||
} as never,
|
||||
});
|
||||
|
||||
expect(summary).toMatchObject({
|
||||
status: "warning",
|
||||
ownerEmail: "owner@example.test",
|
||||
planCode: "business",
|
||||
seatQuantity: 7,
|
||||
billingStatus: "past_due",
|
||||
providerSummaryKey: "admin.accounts.supportConsole.providers.partial",
|
||||
});
|
||||
expect(summary.metrics).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "users", value: "1", href: "/accounts/users?tenantId=tenant_1" }),
|
||||
expect.objectContaining({ id: "billing", value: "past_due", tone: "warning", href: "/system/billing" }),
|
||||
expect.objectContaining({ id: "providers", value: "Lago", tone: "warning", href: "/system/billing" }),
|
||||
])
|
||||
);
|
||||
expect(summary.actions).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "users", href: "/accounts/users?tenantId=tenant_1" }),
|
||||
expect.objectContaining({ id: "audit", href: "/audit?tenantId=tenant_1" }),
|
||||
expect.objectContaining({ id: "events", href: "/events?tenantId=tenant_1" }),
|
||||
])
|
||||
);
|
||||
});
|
||||
});
|
||||
+564
-165
@@ -1,6 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { ActionFunction, Link, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData, useNavigation } from "react-router";
|
||||
import { useActionData, useParams, useSubmit } from "react-router";
|
||||
import { Activity, ArrowRight, CreditCard, ExternalLink, KeyRound, ShieldAlert, Users } from "lucide-react";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant, getTenantBySlug, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
|
||||
@@ -22,53 +23,128 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getAllTenantTypes, getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { AccountUpdatedDto } from "~/modules/events/dtos/AccountUpdatedDto";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import {
|
||||
ADMIN_TENANT_NOTE_CATEGORIES,
|
||||
buildAdminConnectorListVM,
|
||||
buildAdminTenantNoteListVM,
|
||||
type AdminConnectorListVM,
|
||||
type AdminTenantNoteListVM,
|
||||
type ConnectorOverrideState,
|
||||
} from "@hivegrid/view-models";
|
||||
import { AdminTenantOperationsPanel } from "~/components/screens/admin/AdminTenantOperationsPanel";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
import { AdminBillingError, extendTenantTrial } from "~/services/admin/billing-admin.server";
|
||||
import { AdminConnectorError, getTenantConnectorRows, setTenantFeatureConnector } from "~/services/admin/subscription-assembly.server";
|
||||
import { createTenantNote, deleteTenantNote, getTenantNoteRows, TenantNoteError } from "~/services/admin/tenant-notes.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type TenantSupportTone = "success" | "warning" | "danger" | "neutral";
|
||||
|
||||
type TenantSupportMetric = {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
value: string;
|
||||
detailKey: string;
|
||||
tone: TenantSupportTone;
|
||||
href?: string;
|
||||
};
|
||||
|
||||
type TenantSupportAction = {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
detailKey: string;
|
||||
href: string;
|
||||
external?: boolean;
|
||||
};
|
||||
|
||||
type TenantSupportSummary = {
|
||||
status: TenantSupportTone;
|
||||
statusLabelKey: string;
|
||||
statusDetail: string | null;
|
||||
ownerEmail: string | null;
|
||||
planCode: string | null;
|
||||
seatQuantity: number | null;
|
||||
billingStatus: string | null;
|
||||
providerSummaryKey: string;
|
||||
metrics: TenantSupportMetric[];
|
||||
actions: TenantSupportAction[];
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenant: TenantWithDetails;
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
supportSummary: TenantSupportSummary;
|
||||
connectors: AdminConnectorListVM;
|
||||
notes: AdminTenantNoteListVM;
|
||||
trial: { status: string | null; trialEndsAtIso: string | null };
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenant = await getTenant(params.id!);
|
||||
if (!tenant) {
|
||||
const tenantId = params.id;
|
||||
if (!tenantId) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, tenantTypes] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(params.id ?? ""),
|
||||
getAllSubscriptionProducts(),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
tenantTypes,
|
||||
};
|
||||
return data;
|
||||
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, connectorRows, noteRows, trialSubscription] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(tenantId),
|
||||
getAllSubscriptionProducts(),
|
||||
getTenantConnectorRows(tenantId),
|
||||
getTenantNoteRows(tenantId),
|
||||
db.tenantSubscription.findUnique({ where: { tenantId }, select: { status: true, trialEndsAt: true } }),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
supportSummary: buildTenantSupportSummary({ tenant, users, subscription }),
|
||||
connectors: buildAdminConnectorListVM({ rows: connectorRows }),
|
||||
notes: buildAdminTenantNoteListVM({ rows: noteRows }),
|
||||
trial: {
|
||||
status: trialSubscription?.status ?? null,
|
||||
trialEndsAtIso: trialSubscription?.trialEndsAt?.toISOString() ?? null,
|
||||
},
|
||||
};
|
||||
return data;
|
||||
});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
updateSubscriptionSuccess?: string;
|
||||
updateDetailsError?: string;
|
||||
updateSubscriptionError?: string;
|
||||
opsSuccess?: string;
|
||||
opsError?: string;
|
||||
};
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
@@ -83,91 +159,146 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
const tenant = await getTenant(params.id ?? "");
|
||||
if (!tenant) {
|
||||
const tenantId = params.id;
|
||||
if (!tenantId) {
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const icon = form.get("icon")?.toString() ?? "";
|
||||
const typeIds = form.getAll("typeIds[]").map((t) => t.toString());
|
||||
|
||||
if ((name?.length ?? 0) < 1) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.nameRequired"),
|
||||
});
|
||||
}
|
||||
if (!slug || slug.length < 1) {
|
||||
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
let tenantTypes = await getAllTenantTypes();
|
||||
typeIds.forEach((type) => {
|
||||
if (!tenantTypes.find((t) => t.id === type)) {
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const icon = form.get("icon")?.toString() ?? "";
|
||||
|
||||
if ((name?.length ?? 0) < 1) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("admin.accounts.errors.invalidTenantType"),
|
||||
updateDetailsError: t("settings.tenant.errors.nameRequired"),
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!slug || slug.length < 1) {
|
||||
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
|
||||
}
|
||||
|
||||
if (isReservedTenantSlug(slug)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
|
||||
});
|
||||
}
|
||||
if (slug.includes(" ")) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
|
||||
});
|
||||
}
|
||||
|
||||
const existing = await getTenant(params.id!);
|
||||
if (!existing) {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenant") });
|
||||
}
|
||||
|
||||
if (existing.slug !== slug) {
|
||||
const existingSlug = await getTenantBySlug(slug);
|
||||
if (existingSlug) {
|
||||
if (isReservedTenantSlug(slug)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
||||
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
|
||||
});
|
||||
}
|
||||
if (slug.includes(" ")) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.updated",
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
data: {
|
||||
id: tenant.id,
|
||||
new: { name, slug },
|
||||
old: { name: tenant.name, slug: tenant.slug },
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies AccountUpdatedDto,
|
||||
});
|
||||
await updateTenant(existing, { name, icon, slug, typeIds });
|
||||
return Response.json({
|
||||
success: t("settings.tenant.updated"),
|
||||
});
|
||||
} else if (action === "delete-tenant") {
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.deleted",
|
||||
tenantId: null,
|
||||
userId: userInfo.userId,
|
||||
data: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto,
|
||||
});
|
||||
await deleteAndCancelTenant({ tenantId: tenant.id, userId: currentUser.id });
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
} else {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidForm") });
|
||||
}
|
||||
const existing = await getTenant(tenantId);
|
||||
if (!existing) {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenant") });
|
||||
}
|
||||
|
||||
if (existing.slug !== slug) {
|
||||
const existingSlug = await getTenantBySlug(slug);
|
||||
if (existingSlug) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
await EventsService.createTenantEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "account.updated",
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
data: {
|
||||
id: tenant.id,
|
||||
new: { name, slug },
|
||||
old: { name: tenant.name, slug: tenant.slug },
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies AccountUpdatedDto,
|
||||
},
|
||||
() => updateTenant(existing, { name, icon, slug })
|
||||
);
|
||||
return Response.json({
|
||||
intent: "edit",
|
||||
ok: true,
|
||||
messageKey: "admin.accounts.toast.updated",
|
||||
} satisfies ActionData);
|
||||
} else if (action === "trial-extend" || action === "connector-set" || action === "note-create" || action === "note-delete") {
|
||||
const actor = { actorUserId: currentUser.id, actorEmail: currentUser.email, request };
|
||||
try {
|
||||
if (action === "trial-extend") {
|
||||
await extendTenantTrial({
|
||||
tenantId: tenant.id,
|
||||
days: form.get("days")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
...actor,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.tenantOps.trial.extended") } satisfies ActionData);
|
||||
}
|
||||
if (action === "connector-set") {
|
||||
const state = form.get("state")?.toString() ?? "";
|
||||
if (state !== "enabled" && state !== "disabled" && state !== "inherit") {
|
||||
return badRequest({ opsError: t("shared.invalidForm") });
|
||||
}
|
||||
await setTenantFeatureConnector({
|
||||
tenantId: tenant.id,
|
||||
featureKey: form.get("featureKey")?.toString() ?? "",
|
||||
state: state satisfies ConnectorOverrideState,
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
...actor,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.connectors.updated") } satisfies ActionData);
|
||||
}
|
||||
if (action === "note-create") {
|
||||
await createTenantNote({
|
||||
tenantId: tenant.id,
|
||||
noteText: form.get("noteText")?.toString() ?? "",
|
||||
category: form.get("category")?.toString() ?? null,
|
||||
pinned: form.get("pinned")?.toString() === "true",
|
||||
authorUserId: currentUser.id,
|
||||
actorEmail: currentUser.email,
|
||||
request,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.tenantNotes.created") } satisfies ActionData);
|
||||
}
|
||||
await deleteTenantNote({
|
||||
noteId: form.get("noteId")?.toString() ?? "",
|
||||
tenantId: tenant.id,
|
||||
...actor,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.tenantNotes.deleted") } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminActionInputError || error instanceof AdminConnectorError || error instanceof TenantNoteError) {
|
||||
return badRequest({ opsError: t(error.i18nKey) });
|
||||
}
|
||||
if (error instanceof AdminBillingError) {
|
||||
return badRequest({ opsError: t(error.i18nKey) });
|
||||
}
|
||||
// Unexpected failures (e.g. the audit writer refusing an unauditable
|
||||
// action) surface as a Klartext banner instead of a naked 500 page.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("admin tenant-ops action failed", { action, tenantId }, error);
|
||||
return badRequest({ opsError: t("admin.tenantOps.errors.actionFailed") });
|
||||
}
|
||||
} else if (action === "delete-tenant") {
|
||||
await deleteAndCancelTenant({
|
||||
request,
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
eventData: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto,
|
||||
});
|
||||
return redirect(`${adminPath("accounts", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.toast.deleted")}`);
|
||||
} else {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidForm") });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export default function TenantRoute() {
|
||||
@@ -178,6 +309,8 @@ export default function TenantRoute() {
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
useSaveToast(actionData, { intents: ["edit"] });
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const successModal = useRef<RefSuccessModal>(null);
|
||||
@@ -204,59 +337,83 @@ export default function TenantRoute() {
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={data.tenant.name}
|
||||
menu={[
|
||||
{ title: t("models.tenant.plural"), routePath: adminPath("accounts", { mode: "host-aware" }) },
|
||||
{ title: data.tenant?.name ?? "", routePath: adminPath(`accounts/${params.id ?? ""}`, { mode: "host-aware" }) },
|
||||
]}
|
||||
>
|
||||
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UpdateTenantDetailsForm
|
||||
tenant={data.tenant}
|
||||
disabled={!getUserHasPermission(adminData, "admin.account.settings.update")}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader title={data.tenant.name} description={t("admin.accounts.detailPageDescription", { slug: data.tenant.slug })} />
|
||||
<EditPageLayout
|
||||
fullWidth
|
||||
menu={[
|
||||
{ title: t("models.tenant.plural"), routePath: adminPath("accounts", { mode: "host-aware" }) },
|
||||
{ title: data.tenant?.name ?? "", routePath: adminPath(`accounts/${params.id ?? ""}`, { mode: "host-aware" }) },
|
||||
]}
|
||||
>
|
||||
<TenantSupportConsole data={data} />
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tenant Users */}
|
||||
{getUserHasPermission(adminData, "admin.account.users") && (
|
||||
<Fragment>
|
||||
<SettingSection title={t("models.user.plural")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UsersTable
|
||||
items={data.users}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canSetUserRoles={false}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tenant Subscription */}
|
||||
{/* {getUserHasPermission(adminData, "admin.account.subscription") && (
|
||||
{/* AK-P19 DoD #3: trial extension, connector assembly, operator notes */}
|
||||
{getUserHasPermission(adminData, "admin.account.settings.update") && (
|
||||
<Fragment>
|
||||
<AdminTenantOperationsPanel
|
||||
connectors={data.connectors}
|
||||
notes={data.notes}
|
||||
trial={data.trial}
|
||||
noteCategories={ADMIN_TENANT_NOTE_CATEGORIES}
|
||||
csrf={rootData.csrf ?? ""}
|
||||
submitting={navigation.state === "submitting"}
|
||||
feedback={{ success: actionData?.opsSuccess, error: actionData?.opsError }}
|
||||
/>
|
||||
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UpdateTenantDetailsForm tenant={data.tenant} disabled={!getUserHasPermission(adminData, "admin.account.settings.update")} />
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tenant Users */}
|
||||
{getUserHasPermission(adminData, "admin.account.users") && (
|
||||
<Fragment>
|
||||
<SettingSection title={t("models.user.plural")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UsersTable
|
||||
items={data.users}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canSetUserRoles={false}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
{/* Tenant Subscription */}
|
||||
{/* {getUserHasPermission(adminData, "admin.account.subscription") && (
|
||||
<>
|
||||
<div className="md:grid lg:grid-cols-3 md:gap-2">
|
||||
<div className="md:col-span-1">
|
||||
@@ -281,33 +438,275 @@ export default function TenantRoute() {
|
||||
</>
|
||||
)} */}
|
||||
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
<div className="">
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
<div className="">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("admin.accounts.danger.deleteAccountTitle")}</h3>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("admin.accounts.danger.deleteAccountDescription")}</p>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<ButtonPrimary destructive={true} onClick={deleteAccount}>
|
||||
{t("settings.danger.deleteAccount")}
|
||||
</ButtonPrimary>
|
||||
<div className="">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("admin.accounts.danger.deleteAccountTitle")}</h3>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("admin.accounts.danger.deleteAccountDescription")}</p>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<ButtonPrimary destructive={true} onClick={deleteAccount}>
|
||||
{t("settings.danger.deleteAccount")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
)}
|
||||
</SettingSection>
|
||||
)}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
||||
<SuccessModal ref={successModal} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</EditPageLayout>
|
||||
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
||||
<SuccessModal ref={successModal} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</EditPageLayout>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function buildTenantSupportSummary({
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
}: {
|
||||
tenant: TenantWithDetails;
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
}): TenantSupportSummary {
|
||||
const owner = tenant.users.find((item) => item.type === TenantUserType.OWNER)?.user ?? users[0] ?? null;
|
||||
const activeUsers = users.filter((user) =>
|
||||
user.tenants.some((membership) => membership.tenantId === tenant.id && membership.status === TenantUserStatus.ACTIVE)
|
||||
).length;
|
||||
const hasLago = Boolean(subscription?.lagoCustomerId);
|
||||
const hasMollie = Boolean(subscription?.mollieCustomerId);
|
||||
const billingAttention = Boolean(
|
||||
subscription?.status === "past_due" || subscription?.status === "frozen" || subscription?.pastDueSince || subscription?.frozenAt
|
||||
);
|
||||
const status: TenantSupportTone = !tenant.active || tenant.deactivatedReason ? "danger" : billingAttention ? "warning" : "success";
|
||||
|
||||
return {
|
||||
status,
|
||||
statusLabelKey:
|
||||
tenant.active && !tenant.deactivatedReason ? "admin.accounts.supportConsole.status.active" : "admin.accounts.supportConsole.status.inactive",
|
||||
statusDetail: tenant.deactivatedReason,
|
||||
ownerEmail: owner?.email ?? null,
|
||||
planCode: subscription?.planCode ?? null,
|
||||
seatQuantity: subscription?.seatQuantity ?? null,
|
||||
billingStatus: subscription?.status ?? null,
|
||||
providerSummaryKey:
|
||||
hasLago && hasMollie
|
||||
? "admin.accounts.supportConsole.providers.complete"
|
||||
: hasLago || hasMollie
|
||||
? "admin.accounts.supportConsole.providers.partial"
|
||||
: "admin.accounts.supportConsole.providers.missing",
|
||||
metrics: [
|
||||
{
|
||||
id: "users",
|
||||
labelKey: "admin.accounts.supportConsole.metrics.users.label",
|
||||
value: String(activeUsers),
|
||||
detailKey: "admin.accounts.supportConsole.metrics.users.detail",
|
||||
tone: activeUsers > 0 ? "success" : "warning",
|
||||
href: adminPath(`accounts/users?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "billing",
|
||||
labelKey: "admin.accounts.supportConsole.metrics.billing.label",
|
||||
value: subscription?.status ?? "-",
|
||||
detailKey: billingAttention
|
||||
? "admin.accounts.supportConsole.metrics.billing.detailAttention"
|
||||
: "admin.accounts.supportConsole.metrics.billing.detailOk",
|
||||
tone: billingAttention ? "warning" : subscription ? "success" : "neutral",
|
||||
href: adminPath("system/billing", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "providers",
|
||||
labelKey: "admin.accounts.supportConsole.metrics.providers.label",
|
||||
value: [hasLago ? "Lago" : null, hasMollie ? "Mollie" : null].filter(Boolean).join(" / ") || "-",
|
||||
detailKey:
|
||||
hasLago && hasMollie ? "admin.accounts.supportConsole.metrics.providers.detailOk" : "admin.accounts.supportConsole.metrics.providers.detailMissing",
|
||||
tone: hasLago && hasMollie ? "success" : "warning",
|
||||
href: adminPath("system/billing", { mode: "host-aware" }),
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
id: "open-tenant",
|
||||
labelKey: "admin.accounts.supportConsole.actions.openTenant.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.openTenant.detail",
|
||||
href: "",
|
||||
external: true,
|
||||
},
|
||||
{
|
||||
id: "users",
|
||||
labelKey: "admin.accounts.supportConsole.actions.users.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.users.detail",
|
||||
href: adminPath(`accounts/users?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "audit",
|
||||
labelKey: "admin.accounts.supportConsole.actions.audit.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.audit.detail",
|
||||
href: adminPath(`audit?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "security",
|
||||
labelKey: "admin.accounts.supportConsole.actions.security.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.security.detail",
|
||||
href: adminPath(`accounts/${tenant.id}/security`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "events",
|
||||
labelKey: "admin.accounts.supportConsole.actions.events.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.events.detail",
|
||||
href: adminPath(`events?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function TenantSupportConsole({ data }: { data: LoaderData }) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const summary = data.supportSummary;
|
||||
const appHref = absoluteAppPath(rootData.routing, data.tenant.slug, "dashboard");
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Card className="gap-5 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="min-w-0 space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge color={toneToBadgeColor(summary.status)} withColorDot>
|
||||
{t(summary.statusLabelKey)}
|
||||
</Badge>
|
||||
<Badge color={summary.billingStatus === "past_due" || summary.billingStatus === "frozen" ? "yellow" : "gray"} withColorDot>
|
||||
{summary.billingStatus ?? t("admin.accounts.supportConsole.billing.noSubscription")}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-xl leading-7">{t("admin.accounts.supportConsole.title")}</CardTitle>
|
||||
<CardDescription className="mt-1 max-w-3xl leading-5">{t("admin.accounts.supportConsole.description")}</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link
|
||||
to={appHref}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="border-border bg-background hover:bg-surface-neutral-secondary inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
|
||||
>
|
||||
{t("admin.accounts.supportConsole.openInApp")}
|
||||
<ExternalLink className="size-4" aria-hidden="true" />
|
||||
</Link>
|
||||
<Link
|
||||
to={adminPath(`audit?tenantId=${data.tenant.id}`, { mode: "host-aware" })}
|
||||
className="border-border bg-background hover:bg-surface-neutral-secondary inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
|
||||
>
|
||||
{t("admin.accounts.supportConsole.openAudit")}
|
||||
<Activity className="size-4" aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,0.45fr)]">
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
{summary.metrics.map((metric) => (
|
||||
<SupportMetricCard key={metric.id} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
<dl className="bg-background grid gap-3 rounded-md border p-4 text-sm">
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.slug")} value={`/${data.tenant.slug}`} />
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.owner")} value={summary.ownerEmail ?? t("shared.none")} />
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.plan")} value={summary.planCode ?? t("shared.none")} />
|
||||
<SupportDetail
|
||||
label={t("admin.accounts.supportConsole.fields.seats")}
|
||||
value={summary.seatQuantity ? String(summary.seatQuantity) : t("shared.none")}
|
||||
/>
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.providers")} value={t(summary.providerSummaryKey)} />
|
||||
{summary.statusDetail ? (
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.reason")} value={summary.statusDetail} tone="danger" />
|
||||
) : null}
|
||||
</dl>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
|
||||
{summary.actions.map((action) => (
|
||||
<SupportActionCard key={action.id} action={{ ...action, href: action.id === "open-tenant" ? appHref : action.href }} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportMetricCard({ metric }: { metric: TenantSupportMetric }) {
|
||||
const { t } = useTranslation();
|
||||
const content = (
|
||||
<div className="bg-background hover:bg-surface-neutral-secondary/60 flex h-full min-h-28 flex-col justify-between gap-3 rounded-md border p-4 transition-colors">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm leading-5 font-medium">{t(metric.labelKey)}</p>
|
||||
<p className="text-text-neutral-tertiary mt-1 text-xs leading-4">{t(metric.detailKey)}</p>
|
||||
</div>
|
||||
<MetricIcon id={metric.id} tone={metric.tone} />
|
||||
</div>
|
||||
<p className="truncate text-2xl leading-7 font-semibold">{metric.value}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!metric.href) return content;
|
||||
return (
|
||||
<Link to={metric.href} className="focus-visible:shadow-focus block focus-visible:outline-none">
|
||||
{content}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportActionCard({ action }: { action: TenantSupportAction }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Link
|
||||
to={action.href}
|
||||
target={action.external ? "_blank" : undefined}
|
||||
rel={action.external ? "noreferrer" : undefined}
|
||||
className="border-border bg-background hover:bg-surface-neutral-secondary/60 focus-visible:shadow-focus flex min-h-24 items-start justify-between gap-3 rounded-lg border p-4 transition-colors focus-visible:outline-none"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm leading-5 font-medium">{t(action.labelKey)}</p>
|
||||
<p className="text-text-neutral-tertiary mt-1 text-xs leading-4">{t(action.detailKey)}</p>
|
||||
</div>
|
||||
<ArrowRight className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportDetail({ label, value, tone = "neutral" }: { label: string; value: string; tone?: TenantSupportTone }) {
|
||||
return (
|
||||
<div className="grid grid-cols-[7rem_minmax(0,1fr)] gap-3">
|
||||
<dt className="text-text-neutral-tertiary">{label}</dt>
|
||||
<dd className={tone === "danger" ? "text-red-700" : "text-foreground truncate font-medium"}>{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricIcon({ id, tone }: { id: string; tone: TenantSupportTone }) {
|
||||
const className = tone === "danger" ? "text-red-600" : tone === "warning" ? "text-yellow-600" : tone === "success" ? "text-green-600" : "text-gray-500";
|
||||
if (id === "users") return <Users className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
if (id === "billing") return <CreditCard className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
if (id === "providers") return <KeyRound className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
return <ShieldAlert className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function toneToBadgeColor(tone: TenantSupportTone): BadgeColor {
|
||||
if (tone === "success") return "green";
|
||||
if (tone === "danger") return "red";
|
||||
if (tone === "warning") return "yellow";
|
||||
return "gray";
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@ import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { addToBlacklist, findInBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { useSubmit } from "react-router";
|
||||
import { db } from "~/utils/db.server";
|
||||
import DropdownSimple from "~/components/ui/dropdowns/DropdownSimple";
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { findInBlacklist, addToBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { db } from "~/utils/db.server";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
|
||||
-9
@@ -74,7 +74,6 @@ const sourceFiles = [
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users/$user.roles.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/$id.tsx",
|
||||
"apps/web/app/utils/helpers/PermissionsHelper.ts",
|
||||
"apps/web/app/components/core/roles/RolesAndPermissionsMatrix.tsx",
|
||||
@@ -101,14 +100,10 @@ describe("admin account security i18n", () => {
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.deleteSelectedLogs");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.roles");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.permissions");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.adminUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.accountUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.permissions.errors.existingPermission");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.existingRole");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.updateFailed");
|
||||
expect(source).toContain("settings.tenant.errors.nameRequired");
|
||||
expect(source).toContain("settings.tenant.errors.slugRequired");
|
||||
expect(source).toContain("models.blacklist.types.");
|
||||
expect(source).toContain("admin.accounts.users.filters.hasLoggedIn");
|
||||
expect(source).toContain('app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }');
|
||||
@@ -116,16 +111,12 @@ describe("admin account security i18n", () => {
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).toContain("models.permission.matrix.rolePermissionCount");
|
||||
expect(source).toContain("translateLabel(t, i18n, f.title)");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).toContain(
|
||||
'title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).toContain(
|
||||
'title: t("admin.accounts.rolesAndPermissions.tabs.accountUsers")'
|
||||
);
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/admin-users.tsx")).toContain(
|
||||
'title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).not.toContain("i18nT");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/roles.tsx")).not.toContain('from "i18next"');
|
||||
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { action, loader } from "./billing";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key) }),
|
||||
}));
|
||||
vi.mock("~/components/ui/buttons/ButtonPrimary", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/services/admin/billing-admin.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/billing-admin.server")>("~/services/admin/billing-admin.server");
|
||||
return {
|
||||
...actual,
|
||||
listAdminBillingRows: vi.fn(),
|
||||
requestManualBillingSync: vi.fn(),
|
||||
setTenantBillingPlanSeats: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function requestWithForm(form: Record<string, string>) {
|
||||
return new Request("https://admin.example.test/accounts/billing", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams(form),
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin accounts billing route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key),
|
||||
} as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "user_1", email: "ops@hivegrid.de" } as never);
|
||||
vi.mocked(listAdminBillingRows).mockResolvedValue([
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
tenantName: "Acme",
|
||||
tenantSlug: "acme",
|
||||
status: "active",
|
||||
readOnly: false,
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: "mollie_1",
|
||||
lastInvoiceExternalId: "inv_1",
|
||||
lastPaymentExternalId: "pay_1",
|
||||
currentPeriodStart: null,
|
||||
currentPeriodEnd: null,
|
||||
pastDueSince: null,
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
entitlementCount: 1,
|
||||
},
|
||||
] as never);
|
||||
});
|
||||
|
||||
it("checks subscription permission before loading billing rows", async () => {
|
||||
const body = await loader({
|
||||
request: new Request("https://admin.example.test/accounts/billing"),
|
||||
params: {},
|
||||
context: {},
|
||||
} as LoaderFunctionArgs);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.subscription");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(listAdminBillingRows).mock.invocationCallOrder[0]);
|
||||
expect(body.vm.status).toBe("ready");
|
||||
expect(body.vm.data.rows[0].tenantName).toBe("Acme");
|
||||
});
|
||||
|
||||
it("routes plan/seat override actions to the admin service", async () => {
|
||||
const response = (await action({
|
||||
request: requestWithForm({
|
||||
csrf: "csrf",
|
||||
action: "set-plan-seats",
|
||||
tenantId: "tenant_1",
|
||||
planCode: "pro",
|
||||
seatQuantity: "7",
|
||||
reason: "Sonderkunde",
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.planSeatsUpdated" });
|
||||
expect(setTenantBillingPlanSeats).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
planCode: "pro",
|
||||
seatQuantity: "7",
|
||||
reason: "Sonderkunde",
|
||||
actorUserId: "user_1",
|
||||
actorEmail: "ops@hivegrid.de",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("routes manual provider sync actions to the admin service", async () => {
|
||||
const response = (await action({
|
||||
request: requestWithForm({ csrf: "csrf", action: "request-sync", tenantId: "tenant_1", provider: "lago" }),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.syncRequested:admin.billing.providers.lago" });
|
||||
expect(requestManualBillingSync).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }));
|
||||
});
|
||||
});
|
||||
+6
-242
@@ -1,245 +1,9 @@
|
||||
import { buildAdminBillingVM, type AdminBillingRow } from "@hivegrid/view-models";
|
||||
import { ActionFunctionArgs, Form, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData, useNavigation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import {
|
||||
listAdminBillingRows,
|
||||
requestManualBillingSync,
|
||||
setTenantBillingPlanSeats,
|
||||
AdminBillingError,
|
||||
type BillingSyncProvider,
|
||||
} from "~/services/admin/billing-admin.server";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildAdminBillingVM>;
|
||||
};
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/billing");
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = buildAdminBillingVM({ rows: await listAdminBillingRows() });
|
||||
return {
|
||||
title: `${t("admin.billing.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
function billingErrorKey(error: unknown): string {
|
||||
if (error instanceof AdminBillingError || error instanceof AdminActionInputError) return error.i18nKey;
|
||||
return "admin.billing.errors.UNKNOWN";
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const tenantId = form.get("tenantId")?.toString() ?? "";
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
|
||||
try {
|
||||
if (action === "set-plan-seats") {
|
||||
await setTenantBillingPlanSeats({
|
||||
tenantId,
|
||||
planCode: form.get("planCode")?.toString() ?? "",
|
||||
seatQuantity: form.get("seatQuantity")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.planSeatsUpdated") } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (action === "request-sync") {
|
||||
const provider = form.get("provider")?.toString() as BillingSyncProvider;
|
||||
if (provider !== "lago" && provider !== "mollie") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
await requestManualBillingSync({
|
||||
tenantId,
|
||||
provider,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.syncRequested", { provider: t(`admin.billing.providers.${provider}`) }) } satisfies ActionData);
|
||||
}
|
||||
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
} catch (error) {
|
||||
return badRequest({ error: t(billingErrorKey(error)) });
|
||||
}
|
||||
};
|
||||
|
||||
function FieldValue({ label, value }: { label: string; value: string | number | null }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="text-muted-foreground text-xs font-medium uppercase">{label}</div>
|
||||
<div className="text-foreground text-sm break-all">{value || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncButtons({ row, csrf }: { row: AdminBillingRow; csrf?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(["lago", "mollie"] as const).map((provider) => (
|
||||
<Form key={provider} method="post">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="request-sync" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<input type="hidden" name="provider" value={provider} />
|
||||
<ButtonSecondary type="submit" className="h-8 px-3 text-xs">
|
||||
{t("admin.billing.actions.requestProviderSync", { provider: t(`admin.billing.providers.${provider}`) })}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlanSeatForm({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Form method="post" className="grid gap-2 md:grid-cols-[minmax(120px,1fr)_96px_minmax(180px,1.5fr)_auto]">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="set-plan-seats" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.planCode")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="planCode"
|
||||
defaultValue={row.planCode ?? ""}
|
||||
placeholder={t("admin.billing.placeholders.planCode")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.seats")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="seatQuantity"
|
||||
type="number"
|
||||
min={1}
|
||||
defaultValue={row.seatQuantity ?? 1}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.reason")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="reason"
|
||||
placeholder={t("admin.billing.placeholders.reason")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<ButtonPrimary type="submit" disabled={loading} className="h-9 px-3 text-xs">
|
||||
{t("admin.billing.actions.saveOverride")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function BillingRowCard({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="border-border bg-background rounded-md border p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-foreground text-base font-semibold">{row.tenantName}</div>
|
||||
<div className="text-muted-foreground text-sm">{row.tenantSlug}</div>
|
||||
</div>
|
||||
<div className="bg-muted text-foreground rounded-full px-3 py-1 text-xs font-medium">{t(row.statusLabelKey)}</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-4">
|
||||
<FieldValue label={t("admin.billing.fields.planCode")} value={row.planCode} />
|
||||
<FieldValue label={t("admin.billing.fields.seats")} value={row.seatQuantity} />
|
||||
<FieldValue label={t("admin.billing.fields.lastInvoice")} value={row.lastInvoiceExternalId} />
|
||||
<FieldValue label={t("admin.billing.fields.lastPayment")} value={row.lastPaymentExternalId} />
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-3">
|
||||
<FieldValue label={t("admin.billing.fields.readOnlyReason")} value={t(row.readOnlyReasonKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.recoveryHint")} value={t(row.recoveryHintKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.providers")} value={t(row.providerSummaryKey)} />
|
||||
</div>
|
||||
|
||||
<div className="border-border mt-4 border-t pt-4">
|
||||
<PlanSeatForm row={row} csrf={csrf} loading={loading} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<SyncButtons row={row} csrf={csrf} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminBillingRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
const loading = navigation.state === "submitting";
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.rows : [];
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.billing.title")} fullWidth>
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="text-muted-foreground text-sm">{t("admin.billing.description")}</div>
|
||||
{actionData?.success && <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div>}
|
||||
{actionData?.error && <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div>}
|
||||
</div>
|
||||
|
||||
{data.vm.status === "empty" ? (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.billing.empty.headline")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.billing.empty.body")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => (
|
||||
<BillingRowCard key={row.tenantId} row={row} csrf={rootData.csrf} loading={loading} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
export const action = ({ request }: ActionFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/billing");
|
||||
+11
-7
@@ -1,5 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
@@ -19,6 +19,7 @@ import Modal from "~/components/ui/modals/Modal";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -45,13 +46,14 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
@@ -61,25 +63,27 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
return Response.json({ intent: action, ok: true, messageKey: "models.blacklist.toast.created" } satisfies ActionData);
|
||||
} else if (action === "delete") {
|
||||
await deleteFromBlacklist({
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
return Response.json({ intent: action, ok: true, messageKey: "models.blacklist.toast.deleted" } satisfies ActionData);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
return badRequest({ intent: action, errorKey: "shared.invalidForm" });
|
||||
}
|
||||
};
|
||||
|
||||
export default function BlacklistRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const formatters = useLocaleFormatters();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "create";
|
||||
useSaveToast(actionData);
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
|
||||
+308
-14
@@ -1,13 +1,20 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { action, loader } from "./index";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { adminGetAllTenantsWithUsage, getTenantSimple, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames, getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
||||
import { requireUserId } from "~/utils/session.server";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationReissue.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
@@ -29,7 +36,6 @@ vi.mock("~/components/core/tenants/DeactivateTenantModal", () => ({ default: ()
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/forms/FormGroup", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputCheckboxWithDescription", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputText", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
@@ -45,26 +51,44 @@ vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders:
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/api/.server/TenantsApi", () => ({ TenantsApi: { create: vi.fn() } }));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
|
||||
reserveTenantWithoutOwner: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({
|
||||
prepareReservedOwnerInvitation: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/ownerInvitationReissue.server", () => ({
|
||||
getReservedOwnerInvitationReissueTarget: vi.fn(),
|
||||
reissueReservedOwnerInvitation: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrap.constants", () => ({ TENANT_PENDING_OWNER_REASON: "pending_owner" }));
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { slugify: (value: string) => value.toLowerCase() } }));
|
||||
vi.mock("~/utils/csrf", () => ({ appendCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({ useAppOrAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
createTenantUser: vi.fn(),
|
||||
getTenantSimple: vi.fn(),
|
||||
updateTenantDeactivated: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsersNames: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsersNames: vi.fn(), getUser: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getFiltersFromCurrentUrl: vi.fn(),
|
||||
getPaginationFromCurrentUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/tenantService", () => ({ getExistingSlug: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn(), requireUserId: vi.fn() }));
|
||||
vi.mock("~/utils/app/UserValidationUtils", () => ({ default: { validateEmail: vi.fn() } }));
|
||||
|
||||
const OWNER_INVITATION = {
|
||||
issuanceKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
fromUserId: "operator_1",
|
||||
token: "o".repeat(43),
|
||||
mail: { subject: "Einladung", html: `https://app.example.test/invitation/${"o".repeat(43)}` },
|
||||
};
|
||||
const tenants = [
|
||||
{
|
||||
id: "tenant-1",
|
||||
@@ -94,13 +118,25 @@ describe("admin accounts invoice hydration", () => {
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([] as never);
|
||||
vi.mocked(getAllTenantTypes).mockResolvedValue([] as never);
|
||||
vi.mocked(getFiltersFromCurrentUrl).mockReturnValue(undefined as never);
|
||||
vi.mocked(getPaginationFromCurrentUrl).mockReturnValue({ page: 1, pageSize: 10 } as never);
|
||||
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue({
|
||||
items: tenants,
|
||||
pagination: { page: 1, pageSize: 10, totalItems: tenants.length, totalPages: 1 },
|
||||
} as never);
|
||||
vi.mocked(requireUserId).mockResolvedValue("operator_1");
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "operator_1", firstName: "Olivia", locale: "de" } as never);
|
||||
vi.mocked(UserValidationUtils.validateEmail).mockReturnValue(true);
|
||||
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValue(OWNER_INVITATION);
|
||||
vi.mocked(getReservedOwnerInvitationReissueTarget).mockResolvedValue({
|
||||
tenantName: "Heizkraft GmbH",
|
||||
invitationId: "invite-old",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
});
|
||||
vi.mocked(reissueReservedOwnerInvitation).mockResolvedValue({ invitationId: "invite-new", replayed: false });
|
||||
vi.mocked(getTenantSimple).mockResolvedValue({ deactivatedReason: null } as never);
|
||||
});
|
||||
|
||||
it("loads the default tenant list without processor invoice hydration", async () => {
|
||||
@@ -110,5 +146,263 @@ describe("admin accounts invoice hydration", () => {
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.view");
|
||||
expect(body.tenantInvoices).toBeUndefined();
|
||||
expect(body).not.toHaveProperty("includeInvoices");
|
||||
expect(body.reservationRequestKey).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
expect(body.ownerInvitationReissueKey).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
expect(body.ownerInvitationReissueKey).not.toBe(body.reservationRequestKey);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deactivate", false, "billing"],
|
||||
["activate", true, ""],
|
||||
] as const)("runs the %s mutation inside the selected tenant RLS context", async (operation, active, reason) => {
|
||||
vi.mocked(updateTenantDeactivated).mockImplementationOnce(async (tenantId) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
||||
return { id: tenantId } as never;
|
||||
});
|
||||
const form = new FormData();
|
||||
form.set("action", operation);
|
||||
form.set("id", "tenant-1");
|
||||
form.set("reason", reason);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(updateTenantDeactivated).toHaveBeenCalledWith("tenant-1", {
|
||||
active,
|
||||
deactivatedReason: active ? null : "billing",
|
||||
});
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it("atomically reserves an inactive tenant and queues its OWNER invitation", async () => {
|
||||
vi.mocked(reserveTenantWithoutOwner).mockResolvedValue({
|
||||
id: "tenant-reserved",
|
||||
name: "Heizkraft GmbH",
|
||||
slug: "heizkraft",
|
||||
active: false,
|
||||
deactivatedReason: TENANT_PENDING_OWNER_REASON,
|
||||
} as never);
|
||||
const form = new FormData();
|
||||
form.set("action", "create");
|
||||
form.set("name", "Heizkraft GmbH");
|
||||
form.set("slug", "heizkraft");
|
||||
form.set("reservationRequestKey", "d7077797-054b-497a-b1ce-8e4f36257a96");
|
||||
form.set("ownerEmail", "OWNER@HEIZKRAFT.DE");
|
||||
form.set("ownerFirstName", "Anna");
|
||||
form.set("ownerLastName", "Berger");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const result = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(prepareReservedOwnerInvitation).toHaveBeenCalledWith({
|
||||
request,
|
||||
issuanceKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
tenantName: "Heizkraft GmbH",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
issuer: { id: "operator_1", firstName: "Olivia", locale: "de" },
|
||||
});
|
||||
expect(reserveTenantWithoutOwner).toHaveBeenCalledWith({
|
||||
name: "Heizkraft GmbH",
|
||||
slug: "heizkraft",
|
||||
operatorUserId: "operator_1",
|
||||
reservationRequestKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
ownerInvitation: OWNER_INVITATION,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
intent: "create",
|
||||
ok: true,
|
||||
createdTenantId: "tenant-reserved",
|
||||
messageKey: "admin.accounts.toast.ownerInvitationSent",
|
||||
});
|
||||
});
|
||||
|
||||
it("rotates an owner invitation with a page-stable idempotency key", async () => {
|
||||
const issuanceKey = "93923898-e834-41e9-9e2c-0c03080e91df";
|
||||
const reissuedDraft = { ...OWNER_INVITATION, issuanceKey };
|
||||
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValueOnce(reissuedDraft);
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", issuanceKey);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(getReservedOwnerInvitationReissueTarget).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-reserved",
|
||||
operatorUserId: "operator_1",
|
||||
});
|
||||
expect(prepareReservedOwnerInvitation).toHaveBeenCalledWith({
|
||||
request,
|
||||
issuanceKey,
|
||||
tenantName: "Heizkraft GmbH",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
issuer: { id: "operator_1", firstName: "Olivia", locale: "de" },
|
||||
});
|
||||
expect(reissueReservedOwnerInvitation).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-reserved",
|
||||
operatorUserId: "operator_1",
|
||||
sourceInvitationId: "invite-old",
|
||||
ownerInvitation: reissuedDraft,
|
||||
});
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
await expect((response as Response).json()).resolves.toEqual({
|
||||
intent: "resend-owner-invitation",
|
||||
ok: true,
|
||||
messageKey: "admin.accounts.toast.ownerInvitationResent",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a malformed owner-invitation reissue key before loading the reservation", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", "not-a-uuid");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(getReservedOwnerInvitationReissueTarget).not.toHaveBeenCalled();
|
||||
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
expect(reissueReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the ownerless reservation changed before invitation rotation", async () => {
|
||||
vi.mocked(reissueReservedOwnerInvitation).mockRejectedValueOnce(
|
||||
new CatalogError(foundationErrors.idempotencyConflict, { scope: "tenant-owner-invitation-reissue", key: "fixture" })
|
||||
);
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", "93923898-e834-41e9-9e2c-0c03080e91df");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
await expect((response as Response).json()).resolves.toEqual({
|
||||
intent: "resend-owner-invitation",
|
||||
errorKey: "admin.accounts.actions.ownerInvitationResendFailed",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not hide an infrastructure failure as a user conflict", async () => {
|
||||
vi.mocked(reissueReservedOwnerInvitation).mockRejectedValueOnce(new Error("database unavailable"));
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", "93923898-e834-41e9-9e2c-0c03080e91df");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
await expect(action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)).rejects.toThrow(
|
||||
"database unavailable"
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects invalid owner identity before preparing a capability or creating a tenant", async () => {
|
||||
vi.mocked(UserValidationUtils.validateEmail).mockReturnValueOnce(false);
|
||||
const form = new FormData();
|
||||
form.set("action", "create");
|
||||
form.set("name", "Heizkraft GmbH");
|
||||
form.set("slug", "heizkraft");
|
||||
form.set("reservationRequestKey", "d7077797-054b-497a-b1ce-8e4f36257a96");
|
||||
form.set("ownerEmail", "not-an-email");
|
||||
form.set("ownerFirstName", "Anna");
|
||||
form.set("ownerLastName", "Berger");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a malformed reservation request key before creating a tenant", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "create");
|
||||
form.set("name", "Heizkraft GmbH");
|
||||
form.set("slug", "heizkraft");
|
||||
form.set("reservationRequestKey", "attacker-controlled");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["activate", ""],
|
||||
["deactivate", "billing"],
|
||||
] as const)("rejects forged %s of an ownerless reservation without changing its marker", async (operation, reason) => {
|
||||
vi.mocked(getTenantSimple).mockImplementationOnce(async (tenantId) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
||||
return { id: tenantId, active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON } as never;
|
||||
});
|
||||
const form = new FormData();
|
||||
form.set("action", operation);
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("reason", reason);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
await expect((response as Response).json()).resolves.toEqual({
|
||||
intent: operation,
|
||||
errorKey: "admin.accounts.actions.reservationRequiresOwner",
|
||||
});
|
||||
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["activate", "deactivate"] as const)("fails closed when the %s target is not visible through RLS", async (operation) => {
|
||||
vi.mocked(getTenantSimple).mockResolvedValueOnce(null);
|
||||
const form = new FormData();
|
||||
form.set("action", operation);
|
||||
form.set("id", "tenant-hidden");
|
||||
form.set("reason", "billing");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a forged pending_owner reason on a normal tenant", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "deactivate");
|
||||
form.set("id", "tenant-normal");
|
||||
form.set("reason", TENANT_PENDING_OWNER_REASON);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
expect(getTenantSimple).not.toHaveBeenCalled();
|
||||
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+198
-99
@@ -1,37 +1,41 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, createTenantUser, TenantSimple, TenantWithUsage, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, getTenantSimple, TenantSimple, TenantWithUsage, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import TenantsTable from "~/components/core/tenants/TenantsTable";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { adminGetAllUsersNames, getUser } from "~/utils/db/users.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useActionData, useNavigation, useSubmit } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { TenantsApi } from "~/utils/api/.server/TenantsApi";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getExistingSlug } from "~/utils/services/tenantService";
|
||||
import DeactivateTenantModal from "~/components/core/tenants/DeactivateTenantModal";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationReissue.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -41,16 +45,17 @@ type LoaderData = {
|
||||
items: TenantWithUsage[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
reservationRequestKey: string;
|
||||
ownerInvitationReissueKey: string;
|
||||
};
|
||||
|
||||
const RESERVATION_REQUEST_KEY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.accounts");
|
||||
await time(verifyUserHasPermission(request, "admin.accounts.view"), "verifyUserHasPermission");
|
||||
let { t } = await time(getTranslations(request), "getTranslations");
|
||||
const [userOptions, tenantTypes] = await Promise.all([
|
||||
time(adminGetAllUsersNames(), "adminGetAllUsersNames"),
|
||||
time(getAllTenantTypes(), "getAllTenantTypes"),
|
||||
]);
|
||||
const userOptions = await time(adminGetAllUsersNames(), "adminGetAllUsersNames");
|
||||
|
||||
const filterableProperties = [
|
||||
{ name: "name", title: "models.tenant.name" },
|
||||
@@ -66,20 +71,6 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "typeId",
|
||||
title: t("shared.type"),
|
||||
manual: true,
|
||||
options: [
|
||||
{ value: "null", name: t("admin.accounts.filters.defaultType") },
|
||||
...tenantTypes.map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: t(item.title),
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
@@ -90,18 +81,21 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
items: items.sort((a, b) => (a.createdAt > b.createdAt ? -1 : 1)),
|
||||
filterableProperties,
|
||||
pagination,
|
||||
reservationRequestKey: randomUUID(),
|
||||
ownerInvitationReissueKey: randomUUID(),
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
createdTenantId?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
@@ -110,46 +104,119 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (action === "deactivate" && id) {
|
||||
const deactivatedReason = form.get("reason")?.toString();
|
||||
if (!deactivatedReason) {
|
||||
return Response.json({ error: t("admin.accounts.actions.missingDeactivationReason") }, { status: 400 });
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.missingDeactivationReason" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: false,
|
||||
deactivatedReason,
|
||||
if (deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.reservationRequiresOwner" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
const deactivationBlocked = await runWithRlsContext({ tenantId: id }, async () => {
|
||||
const tenant = await getTenantSimple(id);
|
||||
if (!tenant || tenant.deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
||||
return true;
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: false,
|
||||
deactivatedReason,
|
||||
});
|
||||
return false;
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.actions.tenantDeactivated") });
|
||||
if (deactivationBlocked) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.reservationRequiresOwner" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
return Response.json({ intent: action, ok: true, messageKey: "admin.accounts.toast.deactivated" } satisfies ActionData);
|
||||
} else if (action === "activate" && id) {
|
||||
await updateTenantDeactivated(id, {
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
const activationBlocked = await runWithRlsContext({ tenantId: id }, async () => {
|
||||
const tenant = await getTenantSimple(id);
|
||||
if (!tenant || tenant.deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
||||
return true;
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
});
|
||||
return false;
|
||||
});
|
||||
return Response.json({});
|
||||
if (activationBlocked) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.reservationRequiresOwner" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
return Response.json({ intent: action, ok: true, messageKey: "admin.accounts.toast.activated" } satisfies ActionData);
|
||||
} else if (action === "resend-owner-invitation" && id) {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const issuanceKey = form.get("issuanceKey")?.toString() ?? "";
|
||||
if (!RESERVATION_REQUEST_KEY_PATTERN.test(issuanceKey)) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const operatorUserId = await requireUserId(request);
|
||||
const operator = await getUser(operatorUserId);
|
||||
if (!operator) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const target = await getReservedOwnerInvitationReissueTarget({ tenantId: id, operatorUserId });
|
||||
const ownerInvitation = await prepareReservedOwnerInvitation({
|
||||
request,
|
||||
issuanceKey,
|
||||
tenantName: target.tenantName,
|
||||
email: target.email,
|
||||
firstName: target.firstName,
|
||||
lastName: target.lastName,
|
||||
issuer: { id: operator.id, firstName: operator.firstName, locale: operator.locale },
|
||||
});
|
||||
await reissueReservedOwnerInvitation({
|
||||
tenantId: id,
|
||||
operatorUserId,
|
||||
sourceInvitationId: target.invitationId,
|
||||
ownerInvitation,
|
||||
});
|
||||
return Response.json({ intent: action, ok: true, messageKey: "admin.accounts.toast.ownerInvitationResent" } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.ownerInvitationResendFailed" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} else if (action === "create") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const name = form.get("name")?.toString().trim() ?? "";
|
||||
const slug = form.get("slug")?.toString() ?? "";
|
||||
const existingSlug = await getExistingSlug(slug);
|
||||
if (!slug || existingSlug) {
|
||||
return Response.json({ error: t("shared.slugTaken") }, { status: 400 });
|
||||
const reservationRequestKey = form.get("reservationRequestKey")?.toString() ?? "";
|
||||
const ownerEmail = form.get("ownerEmail")?.toString().trim().toLowerCase() ?? "";
|
||||
const ownerFirstName = form.get("ownerFirstName")?.toString().trim() ?? "";
|
||||
const ownerLastName = form.get("ownerLastName")?.toString().trim() ?? "";
|
||||
if (
|
||||
!name ||
|
||||
!slug ||
|
||||
!RESERVATION_REQUEST_KEY_PATTERN.test(reservationRequestKey) ||
|
||||
!UserValidationUtils.validateEmail(ownerEmail) ||
|
||||
!ownerFirstName ||
|
||||
!ownerLastName
|
||||
) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const { tenant, user } = await TenantsApi.create({ request, name, slug });
|
||||
const addMySelf = Boolean(form.get("addMySelf"));
|
||||
if (addMySelf) {
|
||||
const roles = await getAllRoles("app");
|
||||
await createTenantUser(
|
||||
{
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
type: TenantUserType.OWNER,
|
||||
},
|
||||
roles
|
||||
);
|
||||
const operatorUserId = await requireUserId(request);
|
||||
const operator = await getUser(operatorUserId);
|
||||
if (!operator) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const ownerInvitation = await prepareReservedOwnerInvitation({
|
||||
request,
|
||||
issuanceKey: reservationRequestKey,
|
||||
tenantName: name,
|
||||
email: ownerEmail,
|
||||
firstName: ownerFirstName,
|
||||
lastName: ownerLastName,
|
||||
issuer: { id: operator.id, firstName: operator.firstName, locale: operator.locale },
|
||||
});
|
||||
const tenant = await reserveTenantWithoutOwner({ name, slug, operatorUserId, reservationRequestKey, ownerInvitation });
|
||||
const data: ActionData = {
|
||||
intent: action,
|
||||
ok: true,
|
||||
createdTenantId: tenant.id,
|
||||
messageKey: "admin.accounts.toast.ownerInvitationSent",
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -160,6 +227,7 @@ export default function AdminTenantsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
useSaveToast(actionData);
|
||||
|
||||
const [deactivatingTenant, setDeactivatingTenant] = useState<TenantWithUsage>();
|
||||
const [creatingNewAccount, setCreatingNewAccount] = useState(false);
|
||||
@@ -191,36 +259,62 @@ export default function AdminTenantsRoute() {
|
||||
setDeactivatingTenant(undefined);
|
||||
}
|
||||
|
||||
function onResendOwnerInvitation(item: TenantWithUsage) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", item.id);
|
||||
form.set("issuanceKey", data.ownerInvitationReissueKey);
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.tenant.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")}
|
||||
onClick={() => setCreatingNewAccount(true)}
|
||||
>
|
||||
{t("shared.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
onClick: (_idx, item) => onToggleActive(item),
|
||||
disabled: () => navigation.state === "submitting",
|
||||
renderIsDestructive: (i) => !i.deactivatedReason,
|
||||
},
|
||||
]}
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader
|
||||
title={t("models.tenant.plural")}
|
||||
description={t("admin.accounts.pageDescription")}
|
||||
actions={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button type="button" variant="outline" size="sm" disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")} asChild>
|
||||
<Link to={adminPath("accounts/new", { mode: "host-aware" })}>{t("admin.accounts.create.fullCreateLink")}</Link>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")}
|
||||
onClick={() => setCreatingNewAccount(true)}
|
||||
>
|
||||
{t("shared.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<div className="mobile:px-4 flex w-full flex-col gap-3 px-6 py-6">
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
onClick: (_idx, item) => onToggleActive(item),
|
||||
disabled: (item) => navigation.state === "submitting" || item.deactivatedReason === TENANT_PENDING_OWNER_REASON,
|
||||
renderIsDestructive: (i) => !i.deactivatedReason,
|
||||
},
|
||||
{
|
||||
title: t("admin.accounts.actions.resendOwnerInvitation"),
|
||||
onClick: (_idx, item) => onResendOwnerInvitation(item),
|
||||
hidden: (item) => item.deactivatedReason !== TENANT_PENDING_OWNER_REASON || !getUserHasPermission(appOrAdminData, "admin.accounts.create"),
|
||||
disabled: () => navigation.state === "submitting",
|
||||
confirmation: () => ({
|
||||
title: t("admin.accounts.actions.resendOwnerInvitation"),
|
||||
description: t("admin.accounts.actions.resendOwnerInvitationConfirmation"),
|
||||
}),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DeactivateTenantModal
|
||||
open={!!deactivatingTenant}
|
||||
@@ -240,22 +334,22 @@ export default function AdminTenantsRoute() {
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">
|
||||
<CreateTenantForm />
|
||||
<CreateTenantForm reservationRequestKey={data.reservationRequestKey} />
|
||||
</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
|
||||
<ActionResultModal actionData={actionData} />
|
||||
</EditPageLayout>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateTenantForm() {
|
||||
function CreateTenantForm({ reservationRequestKey }: { reservationRequestKey: string }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [addMySelf, setAddMySelf] = useState(true);
|
||||
const [ownerEmail, setOwnerEmail] = useState("");
|
||||
const [ownerFirstName, setOwnerFirstName] = useState("");
|
||||
const [ownerLastName, setOwnerLastName] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setSlug(UrlUtils.slugify(name));
|
||||
@@ -275,16 +369,21 @@ function CreateTenantForm() {
|
||||
}}
|
||||
withErrorModal={false}
|
||||
>
|
||||
<input type="hidden" name="reservationRequestKey" value={reservationRequestKey} readOnly />
|
||||
<div className="space-y-3">
|
||||
<InputText ref={firstInput} autoFocus name="name" title={t("shared.name")} value={name} setValue={setName} required />
|
||||
<InputText name="slug" title={t("shared.slug")} value={slug} setValue={setSlug} required onBlur={() => setSlug(UrlUtils.slugify(slug))} />
|
||||
<InputCheckboxWithDescription
|
||||
name="addMySelf"
|
||||
title={t("admin.accounts.create.addMyselfAsOwner")}
|
||||
description={t("admin.accounts.create.addMyselfAsOwnerDescription")}
|
||||
value={addMySelf}
|
||||
setValue={setAddMySelf}
|
||||
<InputText
|
||||
type="email"
|
||||
name="ownerEmail"
|
||||
title={t("models.user.email")}
|
||||
help={t("admin.accounts.create.ownerInvitationDescription")}
|
||||
value={ownerEmail}
|
||||
setValue={setOwnerEmail}
|
||||
required
|
||||
/>
|
||||
<InputText name="ownerFirstName" title={t("models.user.firstName")} value={ownerFirstName} setValue={setOwnerFirstName} required />
|
||||
<InputText name="ownerLastName" title={t("models.user.lastName")} value={ownerLastName} setValue={setOwnerLastName} required />
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/components/screens/admin/AdminTenantCreatePage", () => ({ AdminTenantCreatePage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ requireUserId: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({ prepareReservedOwnerInvitation: vi.fn() }));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({ reserveTenantWithoutOwner: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-action-audit.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/admin-action-audit.server")>("~/services/admin/admin-action-audit.server");
|
||||
return { ...actual, recordAdminAction: vi.fn() };
|
||||
});
|
||||
vi.mock("~/services/admin/billing-admin.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/billing-admin.server")>("~/services/admin/billing-admin.server");
|
||||
return { ...actual, extendTenantTrial: vi.fn(), setTenantBillingPlanSeats: vi.fn() };
|
||||
});
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { extendTenantTrial, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { action } from "./new";
|
||||
|
||||
const RESERVATION_KEY = "3f2504e0-4f89-41d3-9a0c-0305e82c3301";
|
||||
|
||||
function makeForm(overrides: Record<string, string> = {}): URLSearchParams {
|
||||
return new URLSearchParams({
|
||||
name: "Acme GmbH",
|
||||
slug: "acme-gmbh",
|
||||
reservationRequestKey: RESERVATION_KEY,
|
||||
ownerEmail: "owner@example.test",
|
||||
ownerFirstName: "Owa",
|
||||
ownerLastName: "Ner",
|
||||
planCode: "",
|
||||
seatQuantity: "1",
|
||||
trialDays: "0",
|
||||
reason: "Neukunde aus dem Vertrieb",
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
function makeActionArgs(body: URLSearchParams): ActionFunctionArgs {
|
||||
return {
|
||||
request: new Request("https://admin.example.test/accounts/new", { method: "POST", body }),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs;
|
||||
}
|
||||
|
||||
describe("admin accounts new action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(requireUserId).mockResolvedValue("operator_1");
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "operator_1", email: "op@example.test", firstName: "Op", locale: "de" } as never);
|
||||
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValue({ issuanceKey: RESERVATION_KEY } as never);
|
||||
vi.mocked(reserveTenantWithoutOwner).mockResolvedValue({ id: "tenant_new", slug: "acme-gmbh" } as never);
|
||||
});
|
||||
|
||||
it("requires the create permission and a reason", async () => {
|
||||
const response = (await action(makeActionArgs(makeForm({ reason: "" })))) as Response;
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.create");
|
||||
expect(response.status).toBe(400);
|
||||
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates the reservation, audits tenant.created, and redirects to the detail", async () => {
|
||||
const response = (await action(makeActionArgs(makeForm()))) as Response;
|
||||
|
||||
expect(reserveTenantWithoutOwner).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: "Acme GmbH", slug: "acme-gmbh", operatorUserId: "operator_1", reservationRequestKey: RESERVATION_KEY })
|
||||
);
|
||||
expect(setTenantBillingPlanSeats).not.toHaveBeenCalled();
|
||||
expect(extendTenantTrial).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: "tenant.created", targetId: "tenant_new", reason: "Neukunde aus dem Vertrieb" })
|
||||
);
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain("accounts/tenant_new");
|
||||
expect(response.headers.get("Location")).toContain(`toast=${encodeURIComponent("admin.accounts.toast.created")}`);
|
||||
});
|
||||
|
||||
it("applies optional plan/seats and trial with the same audited reason", async () => {
|
||||
await action(makeActionArgs(makeForm({ planCode: "starter", seatQuantity: "5", trialDays: "30" })));
|
||||
|
||||
expect(setTenantBillingPlanSeats).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantId: "tenant_new", planCode: "starter", seatQuantity: "5", reason: "Neukunde aus dem Vertrieb" })
|
||||
);
|
||||
expect(extendTenantTrial).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_new", days: 30, reason: "Neukunde aus dem Vertrieb" }));
|
||||
});
|
||||
|
||||
it("rejects an invalid owner email before touching the bootstrap service", async () => {
|
||||
const response = (await action(makeActionArgs(makeForm({ ownerEmail: "not-an-email" })))) as Response;
|
||||
expect(response.status).toBe(400);
|
||||
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData, useNavigation } from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { AdminTenantCreatePage } from "~/components/screens/admin/AdminTenantCreatePage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { AdminActionInputError, assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { AdminBillingError, extendTenantTrial, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
const RESERVATION_REQUEST_KEY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
reservationRequestKey: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.accounts.create.title")} | ${process.env.APP_NAME}`,
|
||||
reservationRequestKey: randomUUID(),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData, status = 400) {
|
||||
return Response.json(data, { status });
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const name = form.get("name")?.toString().trim() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const reservationRequestKey = form.get("reservationRequestKey")?.toString() ?? "";
|
||||
const ownerEmail = form.get("ownerEmail")?.toString().trim().toLowerCase() ?? "";
|
||||
const ownerFirstName = form.get("ownerFirstName")?.toString().trim() ?? "";
|
||||
const ownerLastName = form.get("ownerLastName")?.toString().trim() ?? "";
|
||||
const planCode = form.get("planCode")?.toString().trim() ?? "";
|
||||
const seatQuantity = form.get("seatQuantity")?.toString() ?? "1";
|
||||
const trialDays = Number.parseInt(form.get("trialDays")?.toString() ?? "0", 10) || 0;
|
||||
|
||||
if (
|
||||
!name ||
|
||||
!slug ||
|
||||
!RESERVATION_REQUEST_KEY_PATTERN.test(reservationRequestKey) ||
|
||||
!UserValidationUtils.validateEmail(ownerEmail) ||
|
||||
!ownerFirstName ||
|
||||
!ownerLastName
|
||||
) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
if (slug !== UrlUtils.slugify(slug) || isReservedTenantSlug(slug)) {
|
||||
return badRequest({ error: t("settings.tenant.errors.reservedSlug", { slug }) });
|
||||
}
|
||||
|
||||
const operatorUserId = await requireUserId(request);
|
||||
const operator = await getUser(operatorUserId);
|
||||
if (!operator) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
let reason: string;
|
||||
try {
|
||||
reason = assertAdminActionReason(form.get("reason")?.toString());
|
||||
} catch (error) {
|
||||
if (error instanceof AdminActionInputError) return badRequest({ error: t(error.i18nKey) });
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
const ownerInvitation = await prepareReservedOwnerInvitation({
|
||||
request,
|
||||
issuanceKey: reservationRequestKey,
|
||||
tenantName: name,
|
||||
email: ownerEmail,
|
||||
firstName: ownerFirstName,
|
||||
lastName: ownerLastName,
|
||||
issuer: { id: operator.id, firstName: operator.firstName, locale: operator.locale },
|
||||
});
|
||||
const tenant = await reserveTenantWithoutOwner({ name, slug, operatorUserId, reservationRequestKey, ownerInvitation });
|
||||
|
||||
const actor = { actorUserId: operator.id, actorEmail: operator.email, request };
|
||||
if (planCode) {
|
||||
await setTenantBillingPlanSeats({ tenantId: tenant.id, planCode, seatQuantity, reason, ...actor });
|
||||
}
|
||||
if (trialDays > 0) {
|
||||
await extendTenantTrial({ tenantId: tenant.id, days: trialDays, reason, ...actor });
|
||||
}
|
||||
|
||||
await recordAdminAction({
|
||||
action: "tenant.created",
|
||||
targetKind: "tenant",
|
||||
targetId: tenant.id,
|
||||
reason,
|
||||
after: {
|
||||
name,
|
||||
slug,
|
||||
ownerEmail,
|
||||
planCode: planCode || null,
|
||||
trialDays: trialDays || null,
|
||||
},
|
||||
...actor,
|
||||
});
|
||||
|
||||
return redirect(`${adminPath(`accounts/${tenant.id}`, { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.toast.created")}`);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminActionInputError || error instanceof AdminBillingError) {
|
||||
return badRequest({ error: t(error.i18nKey) });
|
||||
}
|
||||
if (error instanceof CatalogError) {
|
||||
return badRequest({ error: t("admin.accounts.create.failed") }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminTenantCreateRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
return (
|
||||
<AdminTenantCreatePage
|
||||
reservationRequestKey={data.reservationRequestKey}
|
||||
csrf={rootData.csrf ?? ""}
|
||||
submitting={navigation.state === "submitting"}
|
||||
feedback={{ error: actionData?.error }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-4
@@ -61,10 +61,6 @@ export default function AdminRolesRoute() {
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.permissions"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.adminUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/admin-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.accountUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }),
|
||||
|
||||
+63
-42
@@ -18,6 +18,8 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
@@ -31,44 +33,52 @@ type LoaderData = {
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenant = await getTenant(params.account!);
|
||||
if (!tenant) {
|
||||
const tenantId = params.account;
|
||||
if (!tenantId) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const adminUsers = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const tenantUsers = await adminGetAllTenantUsers(params.account ?? "");
|
||||
const roles = await getAllRoles("app");
|
||||
|
||||
const items: UserWithRoles[] = [];
|
||||
adminUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }));
|
||||
}
|
||||
});
|
||||
tenantUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
tenant,
|
||||
};
|
||||
return data;
|
||||
const adminUsers = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const tenantUsers = await adminGetAllTenantUsers(tenantId);
|
||||
const roles = await getAllRoles("app");
|
||||
|
||||
const items: UserWithRoles[] = [];
|
||||
adminUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
tenantUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
tenant,
|
||||
};
|
||||
return data;
|
||||
});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
@@ -77,27 +87,37 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
const tenantId = params.account;
|
||||
if (!tenantId) return badRequest({ intent: action, errorKey: "shared.notFound" });
|
||||
|
||||
const tenant = await getTenant(params.account ?? "");
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
const tenantMember = await getTenantMember(userId, tenant?.id);
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
const tenantMember = await getTenantMember(userId, tenant?.id);
|
||||
|
||||
if (!tenant || !user || !role || role.type !== "app" || (!user.admin && !tenantMember)) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (!tenant || !user || !role || role.type !== "app" || (!user.admin && !tenantMember)) {
|
||||
return badRequest({ intent: action, errorKey: "shared.notFound" });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.created", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.deleted", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
}
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.created", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.deleted", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
}
|
||||
|
||||
return Response.json({});
|
||||
return Response.json({
|
||||
intent: action,
|
||||
ok: true,
|
||||
messageKey: add
|
||||
? "admin.accounts.rolesAndPermissions.accountUsers.toast.roleAssigned"
|
||||
: "admin.accounts.rolesAndPermissions.accountUsers.toast.roleRemoved",
|
||||
} satisfies ActionData);
|
||||
});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
return badRequest({ intent: action, errorKey: "shared.invalidForm" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -110,6 +130,7 @@ export default function AdminAccountUsersFromTenant() {
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
useSaveToast(actionData);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
|
||||
+1
-12
@@ -9,7 +9,6 @@ import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -32,7 +31,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAccountUsersRoute() {
|
||||
const { i18n, t } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
@@ -73,16 +72,6 @@ export default function AdminRolesAndPermissionsAccountUsersRoute() {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "types",
|
||||
title: t("shared.types"),
|
||||
value: (i) =>
|
||||
i.types.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t("shared.default")}</span>
|
||||
) : (
|
||||
i.types.map((f) => translateLabel(t, i18n, f.title)).join(", ")
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "users",
|
||||
title: t("models.user.plural"),
|
||||
|
||||
+16
-117
@@ -1,123 +1,22 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllRoles, getRole, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { adminGetAllUsers, getUser, UserWithDetails, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { useEffect, useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithDetails[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
async function redirectToAdminRoleBundles(request: Request) {
|
||||
await requireAdminIdentityPermission(request, "admin_identity.roles.read");
|
||||
throw redirect(adminPath("settings/admin-roles", { mode: "host-aware" }), 303);
|
||||
}
|
||||
|
||||
const items = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const roles = await getAllRoles("admin");
|
||||
export function loader({ request }: LoaderFunctionArgs) {
|
||||
return redirectToAdminRoleBundles(request);
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
export function action({ request }: ActionFunctionArgs) {
|
||||
return redirectToAdminRoleBundles(request);
|
||||
}
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
|
||||
if (!user || !user.admin || !role || role.type !== "admin") {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId);
|
||||
await createAdminLog(request, "admin.adminUserRoles.created", `${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId);
|
||||
await createAdminLog(request, "admin.adminUserRoles.deleted", `${user.email} - ${role.name}`);
|
||||
}
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAdminUsersRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [data]);
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!items) {
|
||||
return [];
|
||||
}
|
||||
return items.filter(
|
||||
(f) =>
|
||||
f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.tenants.find((f) => f.tenant.name.toUpperCase().includes(searchInput.toUpperCase())) ||
|
||||
f.roles.find(
|
||||
(f) => f.role.name.toUpperCase().includes(searchInput.toUpperCase()) || f.role.description.toUpperCase().includes(searchInput.toUpperCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
function onChange(item: UserWithRoles, role: RoleWithPermissions, add: any) {
|
||||
const form = new FormData();
|
||||
form.set("action", "edit");
|
||||
form.set("user-id", item.id);
|
||||
form.set("role-id", role.id);
|
||||
form.set("add", add ? "true" : "false");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<UserRolesTable items={filteredItems()} roles={data.roles} onChange={onChange} disabled={!getUserHasPermission(adminData, "admin.roles.set")} />
|
||||
</div>
|
||||
);
|
||||
export default function LegacyAdminRoleAssignmentRedirect() {
|
||||
return null;
|
||||
}
|
||||
+15
-5
@@ -1,4 +1,4 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useActionData, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllPermissions, PermissionWithRoles, updatePermission } from "~/utils/db/permissions/permissions.db.server";
|
||||
import PermissionsTable from "~/components/core/roles/PermissionsTable";
|
||||
@@ -17,6 +17,7 @@ import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -60,10 +61,13 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
|
||||
type ActionData = {
|
||||
items?: PermissionWithRoles[];
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
@@ -78,20 +82,26 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await updatePermission(id, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ items: await getAllPermissions() });
|
||||
return Response.json({
|
||||
items: await getAllPermissions(),
|
||||
intent: action,
|
||||
ok: true,
|
||||
messageKey: "admin.accounts.rolesAndPermissions.permissions.toast.orderSaved",
|
||||
} satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useLoaderData<ActionData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
useSaveToast(actionData);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
|
||||
+3
-1
@@ -78,7 +78,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
const toastKey =
|
||||
action === "delete" ? "admin.accounts.rolesAndPermissions.permissions.toast.deleted" : "admin.accounts.rolesAndPermissions.permissions.toast.updated";
|
||||
return redirect(`${adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" })}?toast=${encodeURIComponent(toastKey)}`);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+4
-2
@@ -15,7 +15,7 @@ type LoaderData = {
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
@@ -70,7 +70,9 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.rolesAndPermissions.permissions.toast.created")}`
|
||||
);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+6
-11
@@ -21,13 +21,13 @@ describe("admin role assignment scoping", () => {
|
||||
expect(source).not.toContain("deleteUserRole(userId, roleId, params.account)");
|
||||
});
|
||||
|
||||
it("restricts admin user assignments to admin users and admin roles", () => {
|
||||
it("retires legacy UserRole-based admin assignments in favor of AdminRBAC", () => {
|
||||
const source = readRoute("admin-users.tsx");
|
||||
|
||||
expect(source).toContain("!user.admin");
|
||||
expect(source).toContain('role.type !== "admin"');
|
||||
expect(source).toContain("createUserRole(userId, roleId)");
|
||||
expect(source).toContain("deleteUserRole(userId, roleId)");
|
||||
expect(source).toContain("admin_identity.roles.read");
|
||||
expect(source).toContain('adminPath("settings/admin-roles"');
|
||||
expect(source).not.toContain("createUserRole");
|
||||
expect(source).not.toContain("deleteUserRole");
|
||||
});
|
||||
|
||||
it("writes clean role assignment audit details", () => {
|
||||
@@ -36,13 +36,12 @@ describe("admin role assignment scoping", () => {
|
||||
|
||||
expect(adminUsersSource).not.toContain("${role.name}}");
|
||||
expect(accountUsersSource).not.toContain("${role.name}}");
|
||||
expect(adminUsersSource).toContain("`${user.email} - ${role.name}`");
|
||||
expect(adminUsersSource).not.toContain("createAdminLog");
|
||||
expect(accountUsersSource).toContain("`[${tenant.name}] ${user.email} - ${role.name}`");
|
||||
});
|
||||
|
||||
it("uses render-translated stable audit action values", () => {
|
||||
const routeFiles = [
|
||||
"admin-users.tsx",
|
||||
"account-users.$account.tsx",
|
||||
"permissions/new.tsx",
|
||||
"permissions/$id.tsx",
|
||||
@@ -57,8 +56,6 @@ describe("admin role assignment scoping", () => {
|
||||
.filter((action): action is string => typeof action === "string");
|
||||
});
|
||||
|
||||
expect(actions).toContain("admin.adminUserRoles.created");
|
||||
expect(actions).toContain("admin.adminUserRoles.deleted");
|
||||
expect(actions).toContain("admin.accountUserRoles.created");
|
||||
expect(actions).toContain("admin.accountUserRoles.deleted");
|
||||
expect(actions).toContain("admin.roles.updated");
|
||||
@@ -73,8 +70,6 @@ describe("admin role assignment scoping", () => {
|
||||
expect(actions).not.toContain("Deleted");
|
||||
expect(new Set(actions)).toEqual(
|
||||
new Set([
|
||||
"admin.adminUserRoles.created",
|
||||
"admin.adminUserRoles.deleted",
|
||||
"admin.accountUserRoles.created",
|
||||
"admin.accountUserRoles.deleted",
|
||||
"admin.permissions.created",
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
import { LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import RolesTable from "~/components/core/roles/RolesTable";
|
||||
import { getAllRolesWithUsers, RoleWithPermissionsAndUsers } from "~/utils/db/permissions/roles.db.server";
|
||||
|
||||
+5
-3
@@ -10,7 +10,7 @@ import { deleteRole, getRole, RoleWithPermissions, updateRole } from "~/utils/db
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
@@ -78,7 +78,7 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
permissions,
|
||||
})}`
|
||||
);
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
return Response.json({ success: t("admin.accounts.rolesAndPermissions.roles.toast.updated") });
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.updateFailed") }, { status: 400 });
|
||||
}
|
||||
@@ -89,7 +89,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.rolesAndPermissions.roles.toast.deleted")}`
|
||||
);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+4
-2
@@ -15,7 +15,7 @@ type LoaderData = {
|
||||
permissions: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
@@ -72,7 +72,9 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.rolesAndPermissions.roles.toast.created")}`
|
||||
);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+45
-16
@@ -20,13 +20,30 @@ import {
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { MISSING_NUMBER_PLACEHOLDER, toFiniteNumber, useLocaleFormatters } from "~/locale/format";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
// Prisma `Decimal` columns do not reach the browser as numbers: the loader
|
||||
// serialization keeps their structural shape, so a client-side `Number(price)`
|
||||
// evaluates to `NaN` and the tier column renders "NaN €". Normalize the amount
|
||||
// server-side, which is also where every other price surface converts it.
|
||||
function toSerializableSubscriptionProduct(item: TenantSubscriptionProductWithTenant) {
|
||||
return {
|
||||
...item,
|
||||
prices: item.prices.map((price) => ({
|
||||
...price,
|
||||
subscriptionPrice: price.subscriptionPrice ? { ...price.subscriptionPrice, price: Number(price.subscriptionPrice.price) } : null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
type SubscriptionListItem = ReturnType<typeof toSerializableSubscriptionProduct>;
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: TenantSubscriptionProductWithTenant[];
|
||||
items: SubscriptionListItem[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
@@ -74,14 +91,27 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const getFilterValue = (name: string) => filters.properties.find((property) => property.name === name)?.value?.toString();
|
||||
const { items, pagination } = await getAllTenantSubscriptionProducts(
|
||||
{
|
||||
status: getFilterValue("status"),
|
||||
subscriptionProductId: getFilterValue("subscriptionProductId"),
|
||||
tenantId: getFilterValue("tenantId"),
|
||||
},
|
||||
currentPagination
|
||||
const requestedTenantId = getFilterValue("tenantId");
|
||||
const targetTenants = requestedTenantId ? tenantOptions.filter((tenant) => tenant.id === requestedTenantId) : tenantOptions;
|
||||
const tenantPages = await Promise.all(
|
||||
targetTenants.map((tenant) =>
|
||||
runWithRlsContext({ tenantId: tenant.id }, () =>
|
||||
getAllTenantSubscriptionProducts({
|
||||
status: getFilterValue("status"),
|
||||
subscriptionProductId: getFilterValue("subscriptionProductId"),
|
||||
tenantId: tenant.id,
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
const allItems = tenantPages.flatMap((page) => page.items).sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
|
||||
const offset = currentPagination.pageSize * (currentPagination.page - 1);
|
||||
const items = allItems.slice(offset, offset + currentPagination.pageSize).map(toSerializableSubscriptionProduct);
|
||||
const pagination: PaginationDto = {
|
||||
...currentPagination,
|
||||
totalItems: allItems.length,
|
||||
totalPages: Math.ceil(allItems.length / currentPagination.pageSize),
|
||||
};
|
||||
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("models.subscription.plural")} | ${process.env.APP_NAME}` }],
|
||||
@@ -129,13 +159,12 @@ export default function () {
|
||||
<div>
|
||||
{t(product.subscriptionProduct.title)}{" "}
|
||||
{product.prices
|
||||
.map(
|
||||
(f) =>
|
||||
`${formatters.currency(Number(f.subscriptionPrice?.price ?? 0), f.subscriptionPrice?.currency || "USD")} - ${SubscriptionUtils.getBillingPeriodDescription(
|
||||
t,
|
||||
f.subscriptionPrice?.billingPeriod ?? 0
|
||||
)}`
|
||||
)
|
||||
.map((f) => {
|
||||
const amount = toFiniteNumber(f.subscriptionPrice?.price);
|
||||
const amountLabel =
|
||||
amount === null ? MISSING_NUMBER_PLACEHOLDER : formatters.currency(amount, f.subscriptionPrice?.currency || "USD");
|
||||
return `${amountLabel} - ${SubscriptionUtils.getBillingPeriodDescription(t, f.subscriptionPrice?.billingPeriod ?? 0)}`;
|
||||
})
|
||||
.join(", ")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+12
-1
@@ -8,6 +8,8 @@ import { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWi
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: TenantSubscriptionProductWithTenant;
|
||||
@@ -15,7 +17,16 @@ type LoaderData = {
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const item = await adminGetTenantSubscriptionProductById(params.id!);
|
||||
const subscriptionProductId = params.id;
|
||||
if (!subscriptionProductId) {
|
||||
return Response.json({ error: t("admin.accounts.subscriptions.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
const tenantOptions = await adminGetAllTenantsIdsAndNames();
|
||||
let item: TenantSubscriptionProductWithTenant | null = null;
|
||||
for (const tenant of tenantOptions) {
|
||||
item = await runWithRlsContext({ tenantId: tenant.id }, () => adminGetTenantSubscriptionProductById(subscriptionProductId));
|
||||
if (item) break;
|
||||
}
|
||||
if (!item) {
|
||||
return Response.json({ error: t("admin.accounts.subscriptions.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
+113
-144
@@ -1,10 +1,8 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
@@ -16,47 +14,41 @@ vi.mock("react-router", async () => {
|
||||
useOutlet: () => null,
|
||||
};
|
||||
});
|
||||
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn() } }));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => (path ? `/${tenantSlug}/${path}` : `/${tenantSlug}`),
|
||||
adminPath: (path?: string | { mode?: string; path?: string }, options?: { mode?: string }) => {
|
||||
const inputPath = typeof path === "object" ? path.path : path;
|
||||
const mode = typeof path === "object" ? path.mode : options?.mode;
|
||||
const normalizedPath = inputPath ? `/${inputPath.replace(/^\/+/, "")}` : "";
|
||||
return mode === "legacy" ? `/admin${normalizedPath}` : normalizedPath || "/";
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/app/HostRouting.server", () => ({
|
||||
getHostRoutingContextFromRequest: vi.fn(() => "admin"),
|
||||
}));
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: undefined }),
|
||||
}));
|
||||
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
vi.mock("~/components/core/users/UsersTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn() }));
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ getLastUserLog: vi.fn() }));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ getLastUserLogsByUserIds: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getFiltersFromCurrentUrl: vi.fn(),
|
||||
getPaginationFromCurrentUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({
|
||||
enforceAdminMfa: vi.fn(),
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({
|
||||
routing: {
|
||||
appBaseDomain: "example.test",
|
||||
protocol: "https",
|
||||
webAppHost: "app.example.test",
|
||||
adminAppHost: "admin.example.test",
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
|
||||
checkMfaStepUpState: vi.fn(),
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => `/${tenantSlug}${path ? `/${path}` : ""}`,
|
||||
adminPath: (path?: string) => (path ? `/${path}` : "/"),
|
||||
}));
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({ hashPassword: vi.fn(async () => "new-password-hash") }));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({ validatePassword: vi.fn(async () => ({ valid: true, errors: [] })) }));
|
||||
vi.mock("~/services/auth/sessionStore.server", () => ({ revokeAllUserSessionsForUser: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsIdsAndNames: vi.fn(),
|
||||
getTenant: vi.fn(),
|
||||
@@ -64,163 +56,140 @@ vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
adminGetAllUsers: vi.fn(),
|
||||
getUser: vi.fn(),
|
||||
getUserTotpStatus: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-05-08T17:00:00.000Z"),
|
||||
createUserSession: vi.fn(),
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-07-24T17:00:00.000Z"),
|
||||
getUserInfo: vi.fn(),
|
||||
getUserSession: vi.fn(),
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/impersonation-audit.server", () => ({
|
||||
createImpersonationAudit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
vi.mock("~/services/auth/session-handoff.server", () => ({ createSessionHandoffRedirect: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-action-audit.server", () => ({ recordAdminAction: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({ requireAdminIdentityPermission: vi.fn() }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: { createUserEventWithMutation: vi.fn(async (_args, mutation) => mutation()) },
|
||||
}));
|
||||
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { createSessionHandoffRedirect } from "~/services/auth/session-handoff.server";
|
||||
import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getUser, getUserTotpStatus, updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUser, updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action } from "./users";
|
||||
|
||||
const actor = { id: "admin-1", admin: true, email: "admin@example.test" };
|
||||
const targetUser = { id: "user-1", admin: false, email: "user@example.test", defaultTenantId: "tenant-1" };
|
||||
const actorInfo = {
|
||||
userId: actor.id,
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
const adminSession = {
|
||||
id: "admin-session-1",
|
||||
adminUserId: "admin-1",
|
||||
adminUser: { id: "admin-1", email: "admin@example.test" },
|
||||
};
|
||||
const targetUser = {
|
||||
id: "user-1",
|
||||
email: "user@example.test",
|
||||
firstName: "Target",
|
||||
lastName: "User",
|
||||
defaultTenantId: "tenant-1",
|
||||
};
|
||||
const enabledTotpStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:00:00.000Z"), pendingCreatedAt: null };
|
||||
const freshStepUp = { verified: true, state: { userId: actor.id, method: "totp", verifiedAt: "2026-05-08T16:59:00.000Z" }, ageMs: 60_000 };
|
||||
|
||||
function postRequest(actionName = "impersonate", extra: Record<string, string> = {}) {
|
||||
return new Request("https://admin.example.test/accounts/users?filter=active", {
|
||||
return new Request("https://admin.example.test/accounts/users", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: actionName, "user-id": targetUser.id, ...extra }),
|
||||
body: new URLSearchParams({
|
||||
action: actionName,
|
||||
"user-id": targetUser.id,
|
||||
reason: "Supportfall HG-1234 prüfen",
|
||||
...extra,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function callAction(actionName = "impersonate", extra: Record<string, string> = {}) {
|
||||
try {
|
||||
const response = await action({ request: postRequest(actionName, extra), params: {}, context: {}, unstable_pattern: "admin/accounts/users" } as ActionFunctionArgs);
|
||||
return { thrown: false, response: response as Response };
|
||||
} catch (error) {
|
||||
return { thrown: true, response: await (error as Promise<Response>) };
|
||||
}
|
||||
return action({
|
||||
request: postRequest(actionName, extra),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/accounts/users",
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin accounts user impersonation MFA guard", () => {
|
||||
describe("separated AdminUser tenant impersonation", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(requireAdminIdentityPermission).mockResolvedValue(adminSession as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue(actorInfo as never);
|
||||
vi.mocked(getUserSession).mockResolvedValue({ get: vi.fn() } as never);
|
||||
vi.mocked(getUser).mockImplementation(async (id?: string) => (id === actor.id || id === undefined ? actor : id === targetUser.id ? targetUser : null) as never);
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValue(enabledTotpStatus as never);
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue(freshStepUp as never);
|
||||
vi.mocked(enforceAdminMfa).mockImplementation(() => ({ allowed: true, reason: "allowed", redirectTo: "/accounts/users" }) as never);
|
||||
vi.mocked(setLoggedUser).mockResolvedValue({ userId: targetUser.id, defaultTenantId: "tenant-1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue(targetUser as never);
|
||||
vi.mocked(setLoggedUser).mockResolvedValue({
|
||||
userId: targetUser.id,
|
||||
defaultTenantId: "tenant-1",
|
||||
defaultTenant: { id: "tenant-1", slug: "acme" },
|
||||
} as never);
|
||||
vi.mocked(getTenant).mockResolvedValue({ id: "tenant-1", slug: "acme" } as never);
|
||||
vi.mocked(createSessionHandoffRedirect).mockResolvedValue(
|
||||
new Response(null, { status: 302, headers: { Location: "https://app.example.test/auth/session-handoff?code=opaque" } }) as never
|
||||
);
|
||||
vi.mocked(updateUserPassword).mockResolvedValue({} as never);
|
||||
vi.mocked(deleteUserWithItsTenants).mockResolvedValue({ deletedTenants: [] } as never);
|
||||
vi.mocked(createImpersonationAudit).mockResolvedValue({
|
||||
id: "audit-1",
|
||||
createdAt: new Date("2026-05-08T17:00:00.000Z"),
|
||||
actorUserId: actor.id,
|
||||
targetUserId: targetUser.id,
|
||||
tenantId: "tenant-1",
|
||||
action: "start",
|
||||
reason: "admin.users.impersonate",
|
||||
requestPath: "/accounts/users",
|
||||
metadata: null,
|
||||
} as never);
|
||||
vi.mocked(createUserSession).mockResolvedValue(new Response(null, { status: 302, headers: { Location: "/acme/dashboard" } }) as never);
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA step-up before creating an impersonation session", async () => {
|
||||
const result = await callAction();
|
||||
it("uses the smallest permission, reasoned platform audit and a bounded banner marker", async () => {
|
||||
const response = await callAction();
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(result.response).toBeDefined();
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.impersonate");
|
||||
expect(getUserTotpStatus).toHaveBeenCalledWith(actor.id);
|
||||
expect(checkMfaStepUpState).toHaveBeenCalledWith(expect.anything(), actor.id);
|
||||
expect(enforceAdminMfa).toHaveBeenCalledWith(expect.objectContaining({
|
||||
requestUrl: "https://admin.example.test/accounts/users?filter=active",
|
||||
userId: actor.id,
|
||||
isAdmin: true,
|
||||
totpStatus: enabledTotpStatus,
|
||||
stepUp: freshStepUp,
|
||||
redirectMode: "host-aware",
|
||||
}));
|
||||
expect(setLoggedUser).toHaveBeenCalledWith(targetUser);
|
||||
expect(getTenant).toHaveBeenCalledWith("tenant-1");
|
||||
expect(result.response.headers.get("Location")).toBe("/acme/dashboard");
|
||||
expect(response.status).toBe(302);
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin_identity.impersonation.start");
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "impersonation.started",
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetId: targetUser.id,
|
||||
reason: "Supportfall HG-1234 prüfen",
|
||||
})
|
||||
);
|
||||
expect(createSessionHandoffRedirect).toHaveBeenCalledWith({
|
||||
request: expect.any(Request),
|
||||
session: expect.objectContaining({
|
||||
userId: targetUser.id,
|
||||
impersonatingFromAdminUserId: adminSession.adminUserId,
|
||||
impersonatingFromAdminEmail: adminSession.adminUser.email,
|
||||
impersonatingStartedAt: "2026-07-24T17:00:00.000Z",
|
||||
}),
|
||||
redirectTo: "https://app.example.test/acme/dashboard",
|
||||
});
|
||||
});
|
||||
|
||||
it("redirects to the MFA challenge and does not switch sessions when step-up is missing", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction();
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
it("rejects an impersonation without a meaningful operator reason before switching", async () => {
|
||||
const response = await callAction("impersonate", { reason: "x" });
|
||||
expect(response.status).toBe(400);
|
||||
expect(setLoggedUser).not.toHaveBeenCalled();
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
expect(createUserSession).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA before changing a user password", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction("change-password", { "password-new": "new-password-123" });
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(updateUserPassword).not.toHaveBeenCalled();
|
||||
it("uses dedicated AdminRBAC for password reset and revokes the target sessions first", async () => {
|
||||
const response = await callAction("change-password", { "password-new": "new-password-123" });
|
||||
expect(response.status).toBe(200);
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.changePassword");
|
||||
expect(revokeAllUserSessionsForUser).toHaveBeenCalledWith(targetUser.id);
|
||||
expect(updateUserPassword).toHaveBeenCalledWith({ passwordHash: "new-password-hash" }, targetUser.id);
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA before deleting a user", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
it("uses dedicated AdminRBAC for tenant-user deletion", async () => {
|
||||
const response = await callAction("delete-user");
|
||||
expect(response.status).toBe(200);
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.delete");
|
||||
expect(deleteUserWithItsTenants).toHaveBeenCalledWith({
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetUser,
|
||||
request: expect.any(Request),
|
||||
});
|
||||
});
|
||||
|
||||
const result = await callAction("delete-user");
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
||||
it("propagates permission denial as 404 without touching the tenant target", async () => {
|
||||
vi.mocked(requireAdminIdentityPermission).mockRejectedValueOnce(Response.json({}, { status: 404 }));
|
||||
await expect(callAction()).rejects.toMatchObject({ status: 404 });
|
||||
expect(setLoggedUser).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+59
-150
@@ -1,17 +1,13 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { adminGetAllUsers, getUser, getUserTotpStatus, updateUserPassword, UserWithDetails } from "~/utils/db/users.db.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { createImpersonationStartedAt, createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { adminGetAllUsers, getUser, updateUserPassword, UserWithDetails } from "~/utils/db/users.db.server";
|
||||
import { createImpersonationStartedAt, getUserInfo, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import { requireAdminMfaForAction } from "~/services/auth/admin-mfa-gate.server";
|
||||
import UsersTable from "~/components/core/users/UsersTable";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
@@ -19,25 +15,23 @@ import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropert
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { adminGetAllTenantsIdsAndNames, getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import type { Log } from "@hivegrid/db/prisma-browser";
|
||||
import { getLastUserLogsByUserIds } from "~/utils/db/logs.db.server";
|
||||
import { getLastUserLogsByUserIds, type AdminUserLastActivity } from "~/utils/db/logs.db.server";
|
||||
import { useNavigate, useOutlet } from "react-router";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { UserPasswordUpdatedDto } from "~/modules/events/dtos/UserPasswordUpdatedDto";
|
||||
import { UserProfileDeletedDto } from "~/modules/events/dtos/UserProfileDeletedDto";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppPath, absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server";
|
||||
import { createSessionHandoffRedirect } from "~/services/auth/session-handoff.server";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
// export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -48,7 +42,7 @@ type LoaderData = {
|
||||
items: UserWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
lastLogs: { userId: string; log: Log }[];
|
||||
lastLogs: { userId: string; log: AdminUserLastActivity }[];
|
||||
};
|
||||
|
||||
export function adminImpersonationRedirectTarget(
|
||||
@@ -60,7 +54,7 @@ export function adminImpersonationRedirectTarget(
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.users");
|
||||
await time(verifyUserHasPermission(request, "admin.users.view"), "verifyUserHasPermission");
|
||||
await time(requireAdminIdentityPermission(request, "admin.users.view"), "requireAdminIdentityPermission");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
@@ -123,12 +117,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { items, pagination } = await time(adminGetAllUsers(filters, currentPagination), "adminGetAllUsers");
|
||||
|
||||
const lastLogsByUserId = await time(getLastUserLogsByUserIds(items.map((user) => user.id)), "getLastUserLogsByUserIds");
|
||||
const lastLogs: { userId: string; log: Log }[] = items
|
||||
const lastLogs: { userId: string; log: AdminUserLastActivity }[] = items
|
||||
.map((user) => {
|
||||
const log = lastLogsByUserId.get(user.id);
|
||||
return log ? { userId: user.id, log } : null;
|
||||
})
|
||||
.filter((entry): entry is { userId: string; log: Log } => entry !== null);
|
||||
.filter((entry): entry is { userId: string; log: AdminUserLastActivity } => entry !== null);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.user.plural")} | ${process.env.APP_NAME}`,
|
||||
@@ -147,9 +141,7 @@ type ActionData = {
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
await validateCSRFToken(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const form = await request.formData();
|
||||
@@ -162,165 +154,82 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
}
|
||||
switch (action) {
|
||||
case "impersonate": {
|
||||
await verifyUserHasPermission(request, "admin.users.impersonate");
|
||||
// Phase 09 #82 — sensitive-action MFA gate (otpauth from #26).
|
||||
// requireAdminMfaForAction wraps the existing enforceAdminMfa /
|
||||
// step-up plumbing under a typed action taxonomy so future audit
|
||||
// events tag the gate consistently.
|
||||
await requireAdminMfaForAction(request, "impersonation.start", userInfo.userId);
|
||||
await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
|
||||
const userSession = await setLoggedUser(user);
|
||||
if (!userSession) {
|
||||
return badRequest({
|
||||
error: t("shared.notFound"),
|
||||
});
|
||||
const adminSession = await requireAdminIdentityPermission(request, "admin_identity.impersonation.start");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const reason = form.get("reason")?.toString().trim() ?? "";
|
||||
if (reason.length < 10) {
|
||||
return badRequest({ error: t("admin.users.errors.impersonationReasonRequired") });
|
||||
}
|
||||
// Reuse the tenant resolved inside setLoggedUser to avoid a duplicate
|
||||
// getTenant() round-trip on every impersonation start.
|
||||
const userSession = await setLoggedUser(user);
|
||||
const tenant = userSession.defaultTenant ?? (userSession.defaultTenantId ? await getTenant(userSession.defaultTenantId) : null);
|
||||
await createImpersonationAudit({
|
||||
actorUserId: userInfo.userId,
|
||||
targetUserId: user.id,
|
||||
tenantId: tenant?.id ?? userSession.defaultTenantId ?? null,
|
||||
action: "start",
|
||||
reason: "admin.users.impersonate",
|
||||
requestPath: new URL(request.url).pathname,
|
||||
});
|
||||
// Phase 10 Task #67: also emit the consolidated AuditEvent so the
|
||||
// compliance export picks up admin impersonations without joining
|
||||
// the legacy ImpersonationAudit table. ImpersonationAudit remains
|
||||
// for backwards-compat; a future task will retire it.
|
||||
await createAuditEvent({
|
||||
tenantId: tenant?.id ?? userSession.defaultTenantId ?? null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
actorIp: extractWebActorIp(request),
|
||||
actorUserAgent: extractWebActorUserAgent(request),
|
||||
action: "admin.impersonation.start",
|
||||
targetType: "user",
|
||||
await recordAdminAction({
|
||||
action: "impersonation.started",
|
||||
actorUserId: adminSession.adminUserId,
|
||||
actorEmail: adminSession.adminUser.email,
|
||||
targetKind: "tenant-user",
|
||||
targetId: user.id,
|
||||
sourceModule: "admin",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: { requestPath: new URL(request.url).pathname, reason: "admin.users.impersonate" },
|
||||
reason,
|
||||
request,
|
||||
extraMeta: { tenantId: tenant?.id ?? userSession.defaultTenantId ?? null },
|
||||
});
|
||||
return createUserSession(
|
||||
{
|
||||
return createSessionHandoffRedirect({
|
||||
request,
|
||||
session: {
|
||||
...userInfo,
|
||||
...userSession,
|
||||
impersonatingFromUserId: userInfo.userId,
|
||||
impersonatingFromAdminUserId: adminSession.adminUserId,
|
||||
impersonatingFromAdminEmail: adminSession.adminUser.email,
|
||||
impersonatingStartedAt: createImpersonationStartedAt(),
|
||||
},
|
||||
adminImpersonationRedirectTarget(tenant)
|
||||
);
|
||||
redirectTo: adminImpersonationRedirectTarget(tenant),
|
||||
});
|
||||
}
|
||||
case "change-password": {
|
||||
await verifyUserHasPermission(request, "admin.users.changePassword");
|
||||
const actor = await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
const adminSession = await requireAdminIdentityPermission(request, "admin.users.changePassword");
|
||||
const passwordNew = form.get("password-new")?.toString();
|
||||
if (!passwordNew) {
|
||||
return badRequest({ error: t("admin.users.errors.passwordMinLength") });
|
||||
}
|
||||
if (user?.admin) {
|
||||
return badRequest({ error: t("admin.users.errors.cannotChangeAdminPassword") });
|
||||
}
|
||||
const policyResult = await validatePolicyPassword(passwordNew, user?.email ? { email: user.email } : {});
|
||||
const policyResult = await validatePolicyPassword(passwordNew, user.email ? { email: user.email } : {});
|
||||
if (!policyResult.valid) {
|
||||
const first = policyResult.errors[0];
|
||||
return badRequest({ error: first ? t(first.code, first.args ?? {}) : t("admin.users.errors.passwordMinLength") });
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(passwordNew);
|
||||
await updateUserPassword({ passwordHash }, user?.id);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
fromUser: { id: actor?.id ?? "", email: actor?.email ?? "" },
|
||||
} satisfies UserPasswordUpdatedDto,
|
||||
});
|
||||
|
||||
await revokeAllUserSessionsForUser(user.id);
|
||||
await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
userId: adminSession.adminUserId,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
fromUser: { id: adminSession.adminUserId, email: adminSession.adminUser.email },
|
||||
} satisfies UserPasswordUpdatedDto,
|
||||
},
|
||||
() => updateUserPassword({ passwordHash }, user.id)
|
||||
);
|
||||
return success({ success: t("shared.updated") });
|
||||
}
|
||||
case "delete-user": {
|
||||
await verifyUserHasPermission(request, "admin.users.delete");
|
||||
// Phase 09 #82 — destructive admin action (delete user + cascading
|
||||
// tenants) goes through the sensitive-action gate before the existing
|
||||
// step-up enforcement.
|
||||
await requireAdminMfaForAction(request, "tenant.delete", userInfo.userId);
|
||||
await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
const adminSession = await requireAdminIdentityPermission(request, "admin.users.delete");
|
||||
try {
|
||||
const { deletedTenants } = await deleteUserWithItsTenants(userId);
|
||||
const deletedAccounts = await Promise.all(
|
||||
deletedTenants.map(async (tenant) => {
|
||||
const data = {
|
||||
tenant: { id: tenant.id, name: tenant.name },
|
||||
user: { id: user.id, email: user.email },
|
||||
} satisfies AccountDeletedDto;
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.deleted",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
data,
|
||||
});
|
||||
return data;
|
||||
})
|
||||
);
|
||||
await EventsService.create({
|
||||
await deleteUserWithItsTenants({
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetUser: user,
|
||||
request,
|
||||
event: "user.profile.deleted",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
deletedAccounts,
|
||||
} satisfies UserProfileDeletedDto,
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return badRequest({
|
||||
error: t("shared.unexpectedError"),
|
||||
});
|
||||
return badRequest({ error: t("shared.unexpectedError") });
|
||||
}
|
||||
return success({ success: t("shared.deleted") });
|
||||
}
|
||||
default: {
|
||||
default:
|
||||
return badRequest({ error: t("admin.users.errors.invalidForm") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function requireAdminUsersActionMfa(request: Request, actorUserId: string) {
|
||||
const session = await getUserSession(request);
|
||||
const actor = await getUser(actorUserId);
|
||||
const mfaEnforcement = enforceAdminMfa({
|
||||
requestUrl: request.url,
|
||||
userId: actor?.id,
|
||||
isAdmin: Boolean(actor?.admin),
|
||||
totpStatus: actor ? await getUserTotpStatus(actor.id) : null,
|
||||
stepUp: actor ? checkMfaStepUpState(session, actor.id) : { verified: false, reason: "missing" },
|
||||
redirectMode: "host-aware",
|
||||
appFallbackPath: absoluteAppRootPath(loadRequiredWebConfig().routing),
|
||||
});
|
||||
if (mfaEnforcement instanceof Response) {
|
||||
throw mfaEnforcement;
|
||||
}
|
||||
if (!mfaEnforcement.allowed) {
|
||||
throw redirect(mfaEnforcement.redirectTo);
|
||||
}
|
||||
return actor;
|
||||
}
|
||||
|
||||
export default function AdminUsersRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
@@ -344,17 +253,17 @@ export default function AdminUsersRoute() {
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button asChild type="button" variant="default" size="sm">
|
||||
<Link to="new">{t("shared.new")}</Link>
|
||||
<Link to={adminPath("settings/admin-users", { mode: "host-aware" })}>{t("admin.sales.adminUsers.title")}</Link>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<UsersTable
|
||||
items={data.items}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin_identity.impersonation.start")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
canSetUserRoles={adminData.isSuperAdmin}
|
||||
canSetUserRoles={false}
|
||||
pagination={data.pagination}
|
||||
lastLogs={data.lastLogs}
|
||||
/>
|
||||
|
||||
+30
-164
@@ -1,168 +1,34 @@
|
||||
import { Role } from "@hivegrid/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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.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>
|
||||
async function redirectToDedicatedAdminIdentity(request: Request, email: string | undefined) {
|
||||
const adminUser = email
|
||||
? await runAsAdminIdentity(request, "admin_identity.users.manage", () =>
|
||||
db.adminUser.findFirst({
|
||||
where: { email: { equals: email, mode: "insensitive" } },
|
||||
select: { id: true },
|
||||
})
|
||||
)
|
||||
: null;
|
||||
throw redirect(
|
||||
adminPath(adminUser ? `settings/admin-users/${adminUser.id}` : "accounts/users", {
|
||||
mode: "host-aware",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return redirectToDedicatedAdminIdentity(request, params.user);
|
||||
}
|
||||
|
||||
export function action({ request, params }: ActionFunctionArgs) {
|
||||
return redirectToDedicatedAdminIdentity(request, params.user);
|
||||
}
|
||||
|
||||
export default function LegacyAdminUserRolesRedirect() {
|
||||
return null;
|
||||
}
|
||||
+16
-173
@@ -1,179 +1,22 @@
|
||||
import { Role } from "@hivegrid/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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
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;
|
||||
};
|
||||
async function redirectToAuthentikAdminUsers(request: Request) {
|
||||
await requireAdminIdentityPermission(request, "admin_identity.users.manage");
|
||||
throw redirect(adminPath("settings/admin-users", { mode: "host-aware" }), 303);
|
||||
}
|
||||
|
||||
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();
|
||||
export function loader({ request }: LoaderFunctionArgs) {
|
||||
return redirectToAuthentikAdminUsers(request);
|
||||
}
|
||||
|
||||
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();
|
||||
export function action({ request }: ActionFunctionArgs) {
|
||||
return redirectToAuthentikAdminUsers(request);
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
export default function LegacyAdminUserCreationRedirect() {
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user