Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,373 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useParams, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant, getTenantBySlug, getTenantUsers, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import UsersTable from "~/components/core/users/UsersTable";
|
||||
import { adminGetAllTenantUsers, getUser } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
getOrPersistTenantSubscription,
|
||||
getTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId,
|
||||
type TenantSubscriptionWithDetails,
|
||||
} from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { createStripeCustomer, isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { Fragment, useEffect, useRef } from "react";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { deleteAndCancelTenant, isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { findEntityByName, type EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
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";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenant: TenantWithDetails;
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
};
|
||||
|
||||
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) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, tenantSettingsEntity, tenantTypes] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(params.id ?? ""),
|
||||
getAllSubscriptionProducts(),
|
||||
findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity,
|
||||
tenantTypes,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
updateSubscriptionSuccess?: string;
|
||||
updateDetailsError?: string;
|
||||
updateSubscriptionError?: string;
|
||||
};
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const currentUser = await getUser(userInfo.userId);
|
||||
if (!currentUser) {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidUser") });
|
||||
}
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
const tenant = await getTenant(params.id ?? "");
|
||||
if (!tenant) {
|
||||
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") });
|
||||
}
|
||||
|
||||
let tenantTypes = await getAllTenantTypes();
|
||||
typeIds.forEach((type) => {
|
||||
if (!tenantTypes.find((t) => t.id === type)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("admin.accounts.errors.invalidTenantType"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
const tenantSettingsEntity = await findEntityByName({ tenantId: null, name: "tenantSettings" });
|
||||
if (tenantSettingsEntity) {
|
||||
try {
|
||||
await RowsApi.createCustom({
|
||||
entity: tenantSettingsEntity,
|
||||
tenantId: existing.id,
|
||||
t,
|
||||
form,
|
||||
row: existing?.tenantSettingsRow?.row as Parameters<typeof RowsApi.createCustom>[0]["row"],
|
||||
rowCreateInput: { tenantSettingsRow: { create: { tenantId: existing.id } } },
|
||||
request,
|
||||
});
|
||||
} catch {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.updateDetailsFailed") });
|
||||
}
|
||||
}
|
||||
|
||||
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 === "create-stripe-customer") {
|
||||
if (!tenant) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.invalidTenant") });
|
||||
}
|
||||
const tenantUsers = await getTenantUsers(params.id ?? "");
|
||||
if (tenantUsers.length === 0) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noUsers") });
|
||||
}
|
||||
const tenantOwner = tenantUsers.find((user) => user.type === TenantUserType.OWNER);
|
||||
if (!tenantOwner) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noOwner") });
|
||||
}
|
||||
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
||||
if (tenantSubscription.stripeCustomerId) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.customerAlreadySet") });
|
||||
}
|
||||
const stripeCustomer = await createStripeCustomer(tenantOwner.user.email, tenant.name);
|
||||
if (!stripeCustomer) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.createFailed") });
|
||||
}
|
||||
await updateTenantSubscriptionCustomerId(tenant.id, {
|
||||
stripeCustomerId: stripeCustomer.id,
|
||||
});
|
||||
const data: ActionData = {
|
||||
updateSubscriptionSuccess: t("admin.accounts.subscriptionCustomer.actions.created"),
|
||||
};
|
||||
return data;
|
||||
} 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") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function TenantRoute() {
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const successModal = useRef<RefSuccessModal>(null);
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.updateSubscriptionSuccess) {
|
||||
successModal.current?.show(actionData?.updateSubscriptionSuccess);
|
||||
} else if (actionData?.updateSubscriptionError) {
|
||||
errorModal.current?.show(actionData?.updateSubscriptionError);
|
||||
} else if (actionData?.updateDetailsError) {
|
||||
errorModal.current?.show(actionData?.updateDetailsError);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function deleteAccount() {
|
||||
confirmDelete.current?.show(t("settings.danger.confirmDeleteTenant"), t("shared.confirm"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
function confirmDeleteTenant() {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete-tenant");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
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")}
|
||||
tenantSettingsEntity={data.tenantSettingsEntity}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: true,
|
||||
}}
|
||||
/>
|
||||
</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">
|
||||
<div className="sm:px-0">
|
||||
<h3 className="text-lg font-medium leading-6 text-foreground">{t("models.subscriptionProduct.object")}</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 md:mt-0 md:col-span-2">
|
||||
<UpdateTenantSubscriptionForm
|
||||
tenant={data.tenant}
|
||||
subscription={data.subscription}
|
||||
subscriptionProducts={data.subscriptionProducts}
|
||||
isStripeTest={data.isStripeTest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-t border-border"></div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)} */}
|
||||
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
<div className="">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
)}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
||||
<SuccessModal ref={successModal} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
translateIpAddressLogAction,
|
||||
translateIpAddressLogDescription,
|
||||
translateIpAddressLogError,
|
||||
} from "./ip-address-log-labels";
|
||||
|
||||
const t = ((key: string, options?: Record<string, unknown>) => (options?.value ? `${key}:${String(options.value)}` : key)) as TFunction;
|
||||
|
||||
describe("IP address log labels", () => {
|
||||
it("translates known action codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogAction(t, "login")).toBe("admin.accounts.ipAddresses.logs.actions.login");
|
||||
expect(translateIpAddressLogAction(t, "register")).toBe("admin.accounts.ipAddresses.logs.actions.register");
|
||||
expect(translateIpAddressLogAction(t, "reset")).toBe("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
expect(translateIpAddressLogAction(t, "forgot-password")).toBe("admin.accounts.ipAddresses.logs.actions.forgotPassword");
|
||||
expect(translateIpAddressLogAction(t, "reset-password")).toBe("admin.accounts.ipAddresses.logs.actions.resetPassword");
|
||||
expect(translateIpAddressLogAction(t, " custom-action ")).toBe("admin.accounts.ipAddresses.logs.actions.unknownWithValue:custom-action");
|
||||
expect(translateIpAddressLogAction(t, " ")).toBe("");
|
||||
});
|
||||
|
||||
it("translates known description codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogDescription(t, "registration-attempt")).toBe("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
expect(translateIpAddressLogDescription(t, "{empty email}")).toBe("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
expect(translateIpAddressLogDescription(t, "custom description")).toBe("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue:custom description");
|
||||
expect(translateIpAddressLogDescription(t, null)).toBe("");
|
||||
});
|
||||
|
||||
it("translates known error codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogError(t, "blacklisted")).toBe("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
expect(translateIpAddressLogError(t, "Unauthorized.")).toBe("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
expect(translateIpAddressLogError(t, "provider error")).toBe("admin.accounts.ipAddresses.errors.unknownWithValue:provider error");
|
||||
});
|
||||
});
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
export function translateIpAddressLogAction(t: TFunction, action?: string | null) {
|
||||
const normalized = action?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "login") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.login");
|
||||
}
|
||||
if (normalized === "register") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.register");
|
||||
}
|
||||
if (normalized === "reset") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
}
|
||||
if (normalized === "forgot-password") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.forgotPassword");
|
||||
}
|
||||
if (normalized === "reset-password") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.resetPassword");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.logs.actions.unknownWithValue", { value: normalized });
|
||||
}
|
||||
|
||||
export function translateIpAddressLogDescription(t: TFunction, description?: string | null) {
|
||||
const normalized = description?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "registration-attempt") {
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
}
|
||||
if (normalized === "{empty email}") {
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue", { value: normalized });
|
||||
}
|
||||
|
||||
export function translateIpAddressLogError(t: TFunction, error?: string | null) {
|
||||
const normalized = error?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "blacklisted" || normalized === "Blacklisted") {
|
||||
return t("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
}
|
||||
if (normalized === "unauthorized" || normalized === "Unauthorized" || normalized === "Unauthorized.") {
|
||||
return t("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.errors.unknownWithValue", { value: normalized });
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { IpAddressLog } from "@toolctrl/db/prisma-browser";
|
||||
import { getAllIpAddressLogs } from "~/modules/ipAddress/db/ipAddressLogs.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
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 { useSubmit } from "react-router";
|
||||
import { db } from "~/utils/db.server";
|
||||
import DropdownSimple from "~/components/ui/dropdowns/DropdownSimple";
|
||||
import DownArrow from "~/components/ui/icons/DownArrow";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { translateIpAddressLogAction, translateIpAddressLogDescription, translateIpAddressLogError } from "./ip-address-log-labels";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: IpAddressLog[];
|
||||
pagination: PaginationDto;
|
||||
blacklistedIps: string[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.tenantIpAddress.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getAllIpAddressLogs(currentPagination);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.ipAddress.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
blacklistedIps: await db.blacklist
|
||||
.findMany({
|
||||
where: { type: "ip" },
|
||||
select: { value: true },
|
||||
})
|
||||
.then((items) => items.flatMap((i) => i.value)),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action") as string;
|
||||
if (action === "blacklist-ip") {
|
||||
const ip = form.get("ip")?.toString() ?? "";
|
||||
const existing = await findInBlacklist("ip", ip);
|
||||
if (existing) {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.alreadyBlacklisted") }, { status: 400 });
|
||||
} else {
|
||||
await addToBlacklist({
|
||||
type: "ip",
|
||||
value: ip,
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.blacklisted") });
|
||||
}
|
||||
} else if (action === "delete-log") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
await db.ipAddressLog.delete({ where: { id } });
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.logDeleted") });
|
||||
} else if (action === "delete-logs") {
|
||||
const ids = form.getAll("id").map((i) => i.toString());
|
||||
const deleted = await db.ipAddressLog.deleteMany({ where: { id: { in: ids } } });
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.logsDeleted", { count: deleted.count }) });
|
||||
} else {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.invalidAction") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ success?: string; error?: string }>();
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
const [items, setItems] = useState<IpAddressLog[]>(data.items);
|
||||
const [selected, setSelected] = useState<IpAddressLog[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
const selectedCount = selected.length;
|
||||
const formattedSelectedCount = formatters.number(selectedCount);
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.ipAddresses"),
|
||||
routePath: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.logs"),
|
||||
routePath: adminPath("accounts/ip-addresses/logs", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
buttons={<></>}
|
||||
>
|
||||
{selectedCount > 0 && (
|
||||
<DropdownSimple
|
||||
right
|
||||
button={
|
||||
<div className="hover:bg-secondary border-border bg-background text-foreground/80 flex items-center space-x-2 rounded-md border px-2 py-1 text-sm">
|
||||
<div>{t("admin.accounts.ipAddresses.selection.selected", { count: selectedCount, formattedCount: formattedSelectedCount })}</div>
|
||||
<DownArrow className="h-4 w-4" />
|
||||
</div>
|
||||
}
|
||||
items={[
|
||||
{
|
||||
label: t("admin.accounts.ipAddresses.actions.deleteSelectedLogs", { count: selectedCount, formattedCount: formattedSelectedCount }),
|
||||
onClick: () => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-logs");
|
||||
selected.forEach((i) => form.append("id", i.id));
|
||||
setSelected([]);
|
||||
setItems((prev) => prev.filter((p) => !selected.includes(p)));
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<TableSimple
|
||||
items={items}
|
||||
selectedRows={selected}
|
||||
onSelected={setSelected}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.accounts.ipAddresses.actions.blacklistIp"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "blacklist-ip");
|
||||
form.set("ip", i.ip);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
setSelected((prev) => prev.filter((p) => p.id !== i.id));
|
||||
setItems((prev) => prev.filter((p) => p.id !== i.id));
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-log");
|
||||
form.set("id", i.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt),
|
||||
formattedValue: (item) => <span title={formatters.dateTime(item.createdAt)}>{formatters.relativeDate(item.createdAt)}</span>,
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("shared.status"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{i.success ? <SimpleBadge title={t("shared.success")} color={Colors.GREEN} /> : <SimpleBadge title={t("shared.error")} color={Colors.RED} />}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "ip",
|
||||
title: t("models.tenantIpAddress.object"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">
|
||||
{i.ip} {data.blacklistedIps.includes(i.ip) && <SimpleBadge title={t("admin.accounts.ipAddresses.table.blacklisted")} color={Colors.RED} />}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "action",
|
||||
title: t("admin.accounts.ipAddresses.table.action"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{translateIpAddressLogAction(t, i.action)}</div>
|
||||
<div className="text-muted-foreground text-xs">{translateIpAddressLogDescription(t, i.description)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: t("admin.accounts.ipAddresses.table.url"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="">{i.url}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
title: t("admin.accounts.ipAddresses.table.metadata"),
|
||||
value: (i) => (
|
||||
<div className="max-w-xs truncate">
|
||||
{i.metadata ? (
|
||||
<ShowPayloadModalButton description={i.metadata} payload={i.metadata} />
|
||||
) : (
|
||||
<div className="text-muted-foreground italic">{t("shared.notAvailable")}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "error",
|
||||
title: t("shared.error"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col text-red-500">
|
||||
<div className="font-medium">{translateIpAddressLogError(t, i.error)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { IpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import { getAllIpAddresses } from "~/modules/ipAddress/db/ipAddresses.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
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 { db } from "~/utils/db.server";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: IpAddress[];
|
||||
pagination: PaginationDto;
|
||||
blacklistedIps: string[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.tenantIpAddress.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getAllIpAddresses(currentPagination);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.ipAddress.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
blacklistedIps: await db.blacklist
|
||||
.findMany({
|
||||
where: { type: "ip" },
|
||||
select: { value: true },
|
||||
})
|
||||
.then((items) => items.flatMap((i) => i.value)),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action") as string;
|
||||
if (action === "blacklist-ip") {
|
||||
const ip = form.get("ip")?.toString() ?? "";
|
||||
const existing = await findInBlacklist("ip", ip);
|
||||
if (existing) {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.alreadyBlacklisted") }, { status: 400 });
|
||||
} else {
|
||||
await addToBlacklist({
|
||||
type: "ip",
|
||||
value: ip,
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.blacklisted") });
|
||||
}
|
||||
} else if (action === "delete-ip") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
await db.ipAddress.delete({ where: { id } }).then((item) => {
|
||||
clearCacheKey(`ipAddress:${item.ip}`);
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.ipDeleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.invalidAction") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function IpAddresses() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ success?: string; error?: string }>();
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.ipAddresses"),
|
||||
routePath: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.logs"),
|
||||
routePath: adminPath("accounts/ip-addresses/logs", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.accounts.ipAddresses.actions.blacklistIp"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "blacklist-ip");
|
||||
form.set("ip", i.ip);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-ip");
|
||||
form.set("id", i.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "ip",
|
||||
title: t("models.tenantIpAddress.object"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">
|
||||
{i.ip} {i.type && <span className="text-muted-foreground text-xs font-light">({i.type})</span>}{" "}
|
||||
{data.blacklistedIps.includes(i.ip) && <SimpleBadge title={t("admin.accounts.ipAddresses.table.blacklisted")} color={Colors.RED} />}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">{i.provider}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: t("admin.accounts.ipAddresses.table.country"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{i.countryCode}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.countryName}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "region",
|
||||
title: t("admin.accounts.ipAddresses.table.region"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{i.regionCode}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.regionName}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: t("admin.accounts.ipAddresses.table.city"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{i.city}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.zipCode}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
title: t("admin.accounts.ipAddresses.table.metadata"),
|
||||
value: (i) => <div className="max-w-xs truncate">{i.metadata && <ShowPayloadModalButton description={i.metadata} payload={i.metadata} />}</div>,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt),
|
||||
formattedValue: (item) => <span title={formatters.dateTime(item.createdAt)}>{formatters.relativeDate(item.createdAt)}</span>,
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
]}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
const textCache = new Map<string, string>();
|
||||
const jsonCache = new Map<string, unknown>();
|
||||
|
||||
type AdminAccountSecurityTranslations = {
|
||||
admin: {
|
||||
accounts: {
|
||||
rolesAndPermissions: {
|
||||
tabs: {
|
||||
roles: string;
|
||||
permissions: string;
|
||||
adminUsers: string;
|
||||
accountUsers: string;
|
||||
};
|
||||
seed: {
|
||||
tab: string;
|
||||
};
|
||||
};
|
||||
ipAddresses: {
|
||||
actions: Record<string, string>;
|
||||
errors: Record<string, string>;
|
||||
logs: {
|
||||
actions: Record<string, string>;
|
||||
descriptions: Record<string, string>;
|
||||
};
|
||||
table: {
|
||||
blacklisted: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
function resolveRepoPath(file: string) {
|
||||
return path.join(repoRoot, file);
|
||||
}
|
||||
|
||||
function readRepoFile(file: string) {
|
||||
const resolved = resolveRepoPath(file);
|
||||
const cached = textCache.get(resolved);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const source = fs.readFileSync(resolved, "utf8");
|
||||
textCache.set(resolved, source);
|
||||
return source;
|
||||
}
|
||||
|
||||
function readJsonFile<T>(file: string) {
|
||||
const resolved = resolveRepoPath(file);
|
||||
if (!jsonCache.has(resolved)) {
|
||||
jsonCache.set(resolved, JSON.parse(readRepoFile(file)) as unknown);
|
||||
}
|
||||
|
||||
return jsonCache.get(resolved) as T;
|
||||
}
|
||||
|
||||
function readTranslations(locale: "en" | "de") {
|
||||
return readJsonFile<AdminAccountSecurityTranslations>(`apps/web/public/locales/${locale}/translations.json`);
|
||||
}
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-addresses.tsx",
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-address-log-labels.ts",
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-addresses.logs.tsx",
|
||||
"apps/web/app/routes/admin/accounts/blacklist.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/permissions/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/roles/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/roles/$id.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/seed.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.tsx",
|
||||
"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",
|
||||
];
|
||||
|
||||
describe("admin account security i18n", () => {
|
||||
it("uses semantic translation keys for visible account, role, and IP security copy", () => {
|
||||
const source = sourceFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.blacklistIp");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.login");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.register");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.unknownWithValue");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.errors.unknownWithValue");
|
||||
expect(source).toContain('normalized === "blacklisted"');
|
||||
expect(source).toContain('normalized === "unauthorized"');
|
||||
expect(source).toContain("formattedSelectedCount");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.deleteSelectedLogs");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.seed.tab");
|
||||
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.seed.missingTitle");
|
||||
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("admin.accounts.errors.updateDetailsFailed");
|
||||
expect(source).toContain("models.blacklist.types.");
|
||||
expect(source).toContain("admin.accounts.subscriptionCustomer.errors.customerAlreadySet");
|
||||
expect(source).toContain("admin.accounts.subscriptionCustomer.actions.created");
|
||||
expect(source).toContain("admin.accounts.users.filters.hasLoggedIn");
|
||||
expect(source).toContain('app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }');
|
||||
expect(source).toContain("admin.accounts.danger.deleteAccountTitle");
|
||||
expect(source).toContain("admin.permissions.entities.viewPage");
|
||||
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"');
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/permissions.tsx")).not.toContain('from "i18next"');
|
||||
expect(readRepoFile("apps/web/app/components/core/roles/RolesAndPermissionsMatrix.tsx")).not.toContain("i18nT");
|
||||
expect(source).not.toContain('name: "Seed"');
|
||||
expect(source).not.toContain("Existing permission with name:");
|
||||
expect(source).not.toContain("Existing role with name:");
|
||||
expect(source).not.toContain("Role not found with ID:");
|
||||
expect(source).not.toContain("Account name must have at least 1 character");
|
||||
expect(source).not.toContain("Account slug must have at least 1 character");
|
||||
expect(source).not.toContain("Stripe Customer already set");
|
||||
expect(source).not.toContain("Could not create stripe customer");
|
||||
expect(source).not.toContain("Stripe customer created");
|
||||
expect(source).not.toContain('from "~/utils/shared/DateUtils"');
|
||||
expect(source).not.toContain("i.types.map((f) => f.title).join");
|
||||
expect(source).not.toContain("{i.error}");
|
||||
expect(source).not.toContain("{i.action}");
|
||||
expect(source).not.toContain("{i.description}");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).not.toContain(
|
||||
'title: `${t("models.role.adminRoles")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(source).not.toContain('t("models.permission.userRoles")');
|
||||
expect(source).not.toContain('t("models.role.adminRoles")');
|
||||
expect(source).not.toContain('<div className="text-muted-foreground italic">-</div>');
|
||||
expect(source).not.toContain("e.message");
|
||||
expect(source).not.toContain('app.shared.periods.LAST_N_MONTHS", { 0:');
|
||||
expect(source).not.toContain("count: selected.length");
|
||||
});
|
||||
|
||||
it("uses blocked IP wording consistently in the English admin IP copy", () => {
|
||||
const en = readTranslations("en");
|
||||
const ipCopy = en.admin.accounts.ipAddresses;
|
||||
|
||||
expect(ipCopy.table.blacklisted).toBe("Blocked");
|
||||
expect(ipCopy.actions.blacklistIp).toBe("Block IP");
|
||||
expect(ipCopy.actions.alreadyBlacklisted).toBe("IP address is already blocked.");
|
||||
expect(ipCopy.actions.blacklisted).toBe("IP address has been blocked.");
|
||||
});
|
||||
|
||||
it("keeps admin roles and permissions tab copy semantic and locale-specific", () => {
|
||||
const en = readTranslations("en");
|
||||
const de = readTranslations("de");
|
||||
|
||||
expect(en.admin.accounts.rolesAndPermissions.tabs).toEqual({
|
||||
roles: "Roles",
|
||||
permissions: "Permissions",
|
||||
adminUsers: "Admin users",
|
||||
accountUsers: "Account members",
|
||||
});
|
||||
expect(de.admin.accounts.rolesAndPermissions.tabs).toEqual({
|
||||
roles: "Rollen",
|
||||
permissions: "Berechtigungen",
|
||||
adminUsers: "Admin-Nutzer",
|
||||
accountUsers: "Kontomitglieder",
|
||||
});
|
||||
expect(de.admin.accounts.rolesAndPermissions.seed.tab).toBe("Standardwerte");
|
||||
});
|
||||
|
||||
it("keeps admin IP log label locale keys in parity", () => {
|
||||
const en = readTranslations("en");
|
||||
const de = readTranslations("de");
|
||||
|
||||
expect(Object.keys(de.admin.accounts.ipAddresses.logs.actions)).toEqual(Object.keys(en.admin.accounts.ipAddresses.logs.actions));
|
||||
expect(Object.keys(de.admin.accounts.ipAddresses.logs.descriptions)).toEqual(Object.keys(en.admin.accounts.ipAddresses.logs.descriptions));
|
||||
expect(Object.keys(de.admin.accounts.ipAddresses.errors)).toEqual(Object.keys(en.admin.accounts.ipAddresses.errors));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { addToBlacklist, deleteFromBlacklist, getBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { Blacklist } from "@toolctrl/db/prisma-browser";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: Blacklist[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getBlacklist(undefined, currentPagination);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.blacklist.object")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: 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();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create") {
|
||||
await addToBlacklist({
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
} else if (action === "delete") {
|
||||
await deleteFromBlacklist({
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function BlacklistRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const formatters = useLocaleFormatters();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "create";
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdding) {
|
||||
setAdding(false);
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [isAdding]);
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [type, setType] = useState("email");
|
||||
|
||||
function onDelete(item: Blacklist) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
form.set("type", item.type);
|
||||
form.set("value", item.value);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function getColor(type: string) {
|
||||
switch (type) {
|
||||
case "email":
|
||||
return Colors.TEAL;
|
||||
case "domain":
|
||||
return Colors.INDIGO;
|
||||
case "ip":
|
||||
return Colors.RED;
|
||||
default:
|
||||
return Colors.GRAY;
|
||||
}
|
||||
}
|
||||
function getTypeLabel(type: string) {
|
||||
if (type === "email" || type === "domain" || type === "ip") {
|
||||
return t(`models.blacklist.types.${type}`);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.blacklist.object")}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary disabled={isAdding} onClick={() => setAdding(true)}>
|
||||
{t("shared.new")}
|
||||
</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("models.blacklist.type"),
|
||||
value: (i) => i.type,
|
||||
formattedValue: (i) => <SimpleBadge title={getTypeLabel(i.type)} color={getColor(i.type)} />,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: t("models.blacklist.value"),
|
||||
value: (i) => i.value,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "registerAttempts",
|
||||
title: t("models.blacklist.registerAttempts"),
|
||||
value: (i) => i.registerAttempts,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.relativeDate(item.createdAt),
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
onClick: (_, i) => onDelete(i),
|
||||
disabled: () => navigation.state === "loading" || navigation.state === "submitting",
|
||||
},
|
||||
]}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
|
||||
<Modal open={adding} setOpen={() => setAdding(false)} size="md">
|
||||
<h3 className="mb-2 font-medium">{t("shared.add")}</h3>
|
||||
<Form ref={formRef} method="post">
|
||||
<input type="hidden" name="action" value="create" hidden readOnly />
|
||||
<div className="space-y-2">
|
||||
<InputSelect
|
||||
withSearch={false}
|
||||
value={type}
|
||||
setValue={(value) => setType(value?.toString() ?? "")}
|
||||
name="type"
|
||||
title={t("models.blacklist.type")}
|
||||
options={[
|
||||
{ name: t("models.blacklist.types.email"), value: "email" },
|
||||
{ name: t("models.blacklist.types.domain"), value: "domain" },
|
||||
{ name: t("models.blacklist.types.ip"), value: "ip" },
|
||||
]}
|
||||
/>
|
||||
<InputText name="value" title={t("models.blacklist.value")} className="w-full" required defaultValue="" />
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary disabled={isAdding} type="submit">
|
||||
{t("shared.add")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { findEntityByName } from "~/utils/db/entities/entities.db.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 { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getStripeInvoices } from "~/utils/stripe.server";
|
||||
|
||||
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 {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useActionData: () => undefined,
|
||||
useLoaderData: () => ({}),
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useSubmit: () => vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/core/tenants/DeactivateTenantModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/entities/rows/RowProperties", () => ({ 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 }));
|
||||
vi.mock("~/components/ui/modals/ActionResultModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
||||
createMetrics: vi.fn(async () => ({
|
||||
time: async <T,>(value: T | Promise<T>) => value,
|
||||
getServerTimingHeader: () => ({ "Server-Timing": "admin.accounts;dur=1" }),
|
||||
})),
|
||||
}));
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/api/.server/TenantsApi", () => ({ TenantsApi: { create: vi.fn() } }));
|
||||
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/entities/entities.db.server", () => ({ findEntityByName: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
createTenantUser: 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/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/stripe.server", () => ({
|
||||
getStripeInvoices: vi.fn(),
|
||||
isStripeTestMode: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
const tenants = [
|
||||
{
|
||||
id: "tenant-1",
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
createdAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
subscription: { stripeCustomerId: "cus_1" },
|
||||
},
|
||||
{
|
||||
id: "tenant-2",
|
||||
name: "Beta",
|
||||
slug: "beta",
|
||||
createdAt: new Date("2026-05-02T00:00:00.000Z"),
|
||||
subscription: null,
|
||||
},
|
||||
];
|
||||
|
||||
function callLoader(url = "https://admin.example.test/accounts") {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as LoaderFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin accounts invoice hydration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
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(findEntityByName).mockResolvedValue(null as never);
|
||||
vi.mocked(getStripeInvoices).mockResolvedValue([{ id: "in_1", customer: "cus_1" }] as never);
|
||||
});
|
||||
|
||||
it("does not load Stripe invoices for the default tenant list", async () => {
|
||||
const response = await callLoader();
|
||||
const body = await response.json();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.view");
|
||||
expect(getStripeInvoices).not.toHaveBeenCalled();
|
||||
expect(body.tenantInvoices).toBeUndefined();
|
||||
expect(body.includeInvoices).toBe(false);
|
||||
});
|
||||
|
||||
it("loads invoices only when includeInvoices is explicitly requested", async () => {
|
||||
const response = await callLoader("https://admin.example.test/accounts?includeInvoices=true");
|
||||
const body = await response.json();
|
||||
|
||||
expect(getStripeInvoices).toHaveBeenCalledTimes(1);
|
||||
expect(getStripeInvoices).toHaveBeenCalledWith("cus_1", { limit: 10 });
|
||||
expect(body.tenantInvoices).toEqual([{ id: "in_1", customer: "cus_1" }]);
|
||||
expect(body.includeInvoices).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, createTenantUser, 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 { 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 { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useActionData, useLocation, useNavigation, useSubmit } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import type Stripe from "stripe";
|
||||
import { getStripeInvoices, isStripeTestMode } from "~/utils/stripe.server";
|
||||
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 SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { EntityWithDetails, findEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
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 RowProperties from "~/components/entities/rows/RowProperties";
|
||||
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 { appendCSRFToken } from "~/utils/csrf";
|
||||
import { mapWithConcurrency } from "@toolctrl/foundation";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
const ADMIN_TENANT_INVOICE_HYDRATION_CONCURRENCY = 3;
|
||||
const ADMIN_TENANT_INVOICE_LIST_LIMIT = 10;
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: TenantWithUsage[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
tenantInvoices?: Stripe.Invoice[];
|
||||
includeInvoices: boolean;
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
};
|
||||
|
||||
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 filterableProperties = [
|
||||
{ name: "name", title: "models.tenant.name" },
|
||||
{ name: "slug", title: "models.tenant.slug" },
|
||||
{
|
||||
name: "userId",
|
||||
title: "models.user.object",
|
||||
manual: true,
|
||||
options: userOptions.map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.email,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
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;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await time(adminGetAllTenantsWithUsage(filters, currentPagination), "adminGetAllTenantsWithUsage");
|
||||
const includeInvoices = ["1", "true"].includes((urlSearchParams.get("includeInvoices") ?? "").toLowerCase());
|
||||
|
||||
let tenantInvoices: Stripe.Invoice[] | undefined;
|
||||
if (includeInvoices) {
|
||||
tenantInvoices = [];
|
||||
await time(
|
||||
mapWithConcurrency(items, ADMIN_TENANT_INVOICE_HYDRATION_CONCURRENCY, async (item) => {
|
||||
if (item.subscription?.stripeCustomerId) {
|
||||
const invoices = await getStripeInvoices(item.subscription.stripeCustomerId, { limit: ADMIN_TENANT_INVOICE_LIST_LIMIT });
|
||||
tenantInvoices?.push(...invoices);
|
||||
}
|
||||
}),
|
||||
"getStripeInvoices[adminTenantList]"
|
||||
);
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.plural")} | ${process.env.APP_NAME}`,
|
||||
items: items.sort((a, b) => (a.createdAt > b.createdAt ? -1 : 1)),
|
||||
filterableProperties,
|
||||
pagination,
|
||||
tenantInvoices,
|
||||
includeInvoices,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity: await findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: 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();
|
||||
const action = form.get("action")?.toString();
|
||||
const id = form.get("id")?.toString();
|
||||
if (action === "deactivate" && id) {
|
||||
const deactivatedReason = form.get("reason")?.toString();
|
||||
if (!deactivatedReason) {
|
||||
return Response.json({ error: t("admin.accounts.actions.missingDeactivationReason") }, { status: 400 });
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: false,
|
||||
deactivatedReason,
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.actions.tenantDeactivated") });
|
||||
} else if (action === "activate" && id) {
|
||||
await updateTenantDeactivated(id, {
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
});
|
||||
return Response.json({});
|
||||
} else if (action === "create") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = form.get("slug")?.toString() ?? "";
|
||||
const existingSlug = await getExistingSlug(slug);
|
||||
if (!slug || existingSlug) {
|
||||
return Response.json({ error: t("shared.slugTaken") }, { status: 400 });
|
||||
}
|
||||
const { tenant, user } = await TenantsApi.create({ request, form, 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 data: ActionData = {
|
||||
createdTenantId: tenant.id,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminTenantsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
|
||||
const [deactivatingTenant, setDeactivatingTenant] = useState<TenantWithUsage>();
|
||||
const [creatingNewAccount, setCreatingNewAccount] = useState(false);
|
||||
const invoiceToggleHref = buildIncludeInvoicesHref(location.search, !data.includeInvoices);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.createdTenantId) {
|
||||
setCreatingNewAccount(false);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onToggleActive(item: TenantWithUsage) {
|
||||
if (!item.deactivatedReason) {
|
||||
setDeactivatingTenant(item);
|
||||
} else {
|
||||
onConfirmedToggleActive(item, "", true);
|
||||
}
|
||||
}
|
||||
|
||||
function onConfirmedToggleActive(value: TenantSimple, reason: string, activate: boolean) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", !activate ? "deactivate" : "activate");
|
||||
form.set("reason", reason ?? "");
|
||||
form.set("id", value.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
|
||||
setDeactivatingTenant(undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.tenant.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button type="button" variant="outline" size="sm" asChild>
|
||||
<Link to={invoiceToggleHref}>
|
||||
{t(data.includeInvoices ? "shared.hide" : "shared.show")} {t("app.subscription.invoices.title")}
|
||||
</Link>
|
||||
</Button>
|
||||
<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}
|
||||
tenantInvoices={data.tenantInvoices}
|
||||
isStripeTest={data.isStripeTest}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
onClick: (_idx, item) => onToggleActive(item),
|
||||
disabled: () => navigation.state === "submitting",
|
||||
renderIsDestructive: (i) => !i.deactivatedReason,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<DeactivateTenantModal
|
||||
open={!!deactivatingTenant}
|
||||
onClose={() => setDeactivatingTenant(undefined)}
|
||||
item={deactivatingTenant}
|
||||
onConfirm={(item, reason) => onConfirmedToggleActive(item, reason, false)}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={t("admin.accounts.create.title")}
|
||||
open={creatingNewAccount}
|
||||
onClose={() => {
|
||||
setCreatingNewAccount(false);
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">
|
||||
<CreateTenantForm tenantSettingsEntity={data.tenantSettingsEntity} />
|
||||
</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
|
||||
<ActionResultModal actionData={actionData} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function buildIncludeInvoicesHref(search: string, includeInvoices: boolean): string {
|
||||
const params = new URLSearchParams(search);
|
||||
if (includeInvoices) {
|
||||
params.set("includeInvoices", "true");
|
||||
} else {
|
||||
params.delete("includeInvoices");
|
||||
}
|
||||
const nextSearch = params.toString();
|
||||
return nextSearch ? `?${nextSearch}` : "?";
|
||||
}
|
||||
|
||||
function CreateTenantForm({ tenantSettingsEntity }: { tenantSettingsEntity: EntityWithDetails | null }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [addMySelf, setAddMySelf] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setSlug(UrlUtils.slugify(name));
|
||||
}, [name]);
|
||||
|
||||
const firstInput = useRef<RefInputText>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
firstInput.current?.input.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<FormGroup
|
||||
labels={{
|
||||
create: t("shared.create"),
|
||||
}}
|
||||
withErrorModal={false}
|
||||
>
|
||||
<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))} />
|
||||
{tenantSettingsEntity && (
|
||||
<div className="col-span-6 sm:col-span-6">
|
||||
<RowProperties entity={tenantSettingsEntity} item={null} />
|
||||
</div>
|
||||
)}
|
||||
<InputCheckboxWithDescription
|
||||
name="addMySelf"
|
||||
title={t("admin.accounts.create.addMyselfAsOwner")}
|
||||
description={t("admin.accounts.create.addMyselfAsOwnerDescription")}
|
||||
value={addMySelf}
|
||||
setValue={setAddMySelf}
|
||||
/>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect } from "react-router";
|
||||
import { Outlet, useLocation, useNavigate } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useEffect } from "react";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export function isAdminRolesAndPermissionsRootPath(pathname: string) {
|
||||
return UrlUtils.stripTrailingSlash(pathname) === adminPath("accounts/roles-and-permissions", { mode: "host-aware" });
|
||||
}
|
||||
|
||||
export function adminRolesAndPermissionsRedirectTarget() {
|
||||
return adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" });
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
if (isAdminRolesAndPermissionsRootPath(new URL(request.url).pathname)) {
|
||||
throw redirect(adminRolesAndPermissionsRedirectTarget());
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.plural")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesRoute() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdminRolesAndPermissionsRootPath(location.pathname)) {
|
||||
navigate(adminRolesAndPermissionsRedirectTarget());
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
// title={t("app.sidebar.rolesAndPermissions")}
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.roles"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
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" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.seed.tab"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/seed", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useParams, useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { adminGetAllTenantUsers, adminGetAllUsers, getUser, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { useEffect, useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenant, getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import BreadcrumbSimple from "~/components/ui/breadcrumbs/BreadcrumbSimple";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenant: Tenant;
|
||||
items: UserWithRoles[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
});
|
||||
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;
|
||||
};
|
||||
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 tenant = await getTenant(params.account ?? "");
|
||||
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 (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({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminAccountUsersFromTenant() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [actionData, 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.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">
|
||||
<BreadcrumbSimple
|
||||
home={adminPath(undefined, { mode: "host-aware" })}
|
||||
menu={[
|
||||
{
|
||||
title: t("admin.accounts.rolesAndPermissions.tabs.accountUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
title: data.tenant.name,
|
||||
routePath: adminPath(`accounts/roles-and-permissions/account-users/${data.tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<UserRolesTable
|
||||
items={filteredItems()}
|
||||
roles={data.roles}
|
||||
onChange={onChange}
|
||||
tenantId={params.account ?? ""}
|
||||
disabled={!getUserHasPermission(adminData, "admin.roles.set")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetAllTenants, TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useState } from "react";
|
||||
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;
|
||||
tenants: TenantWithDetails[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenants = await adminGetAllTenants();
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
tenants,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAccountUsersRoute() {
|
||||
const { i18n, t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!data.tenants) {
|
||||
return [];
|
||||
}
|
||||
return data.tenants.filter(
|
||||
(f) =>
|
||||
f.name?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.users.find(
|
||||
(x) =>
|
||||
x.user.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
x.user.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
x.user.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<TableSimple
|
||||
items={filteredItems()}
|
||||
headers={[
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("models.tenant.object"),
|
||||
value: (i) => (
|
||||
<div className="max-w-sm truncate">
|
||||
<div className="text-foreground flex items-center space-x-1 truncate font-medium">{i.name}</div>
|
||||
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span>/{i.slug}</span>
|
||||
</div>
|
||||
</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"),
|
||||
className: "max-w-xs truncate",
|
||||
value: (i) => i.users.map((f) => f.user.email).join(", "),
|
||||
href: (i) => adminPath(`accounts/users?tenantId=${i.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => i.createdAt,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.date(item.createdAt, { dateStyle: "medium" })}</div>
|
||||
<div className="text-xs">{formatters.relativeDate(item.createdAt)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.setUserRoles"),
|
||||
onClickRoute: (_, item) => `${item.id}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
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";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithDetails[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const items = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const roles = await getAllRoles("admin");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, 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";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getFiltersFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getAllRolesNames } from "~/utils/db/permissions/roles.db.server";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: PermissionWithRoles[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.roles-and-permissions.permissions");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{ name: "name", title: "models.permission.name" },
|
||||
{ name: "description", title: "models.permission.description" },
|
||||
{
|
||||
name: "roleId",
|
||||
title: "models.role.object",
|
||||
manual: true,
|
||||
options: (await time(getAllRolesNames(), "getAllRolesNames")).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const items = await time(getAllPermissions(undefined, filters), "getAllPermissions");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.permission.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
filterableProperties,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
items?: PermissionWithRoles[];
|
||||
};
|
||||
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();
|
||||
|
||||
if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updatePermission(id, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ items: await getAllPermissions() });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useLoaderData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex space-x-2">
|
||||
<div className="grow">
|
||||
<InputSearchWithURL />
|
||||
</div>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
<ButtonPrimary to="new">
|
||||
<div className="sm:text-sm">+</div>
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
<PermissionsTable
|
||||
// canReorder={true}
|
||||
items={actionData?.items ?? data.items}
|
||||
canCreate={getUserHasPermission(adminData, "admin.roles.create")}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.roles.update")}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("shared.edit") : t("shared.new")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-lg"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import PermissionForm from "~/components/core/roles/PermissionForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { deletePermission, getPermission, PermissionWithRoles, updatePermission } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setPermissionRoles } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { getAllRoles, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
item: PermissionWithRoles;
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getPermission(params.id ?? "");
|
||||
if (!item) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
const roles = await getAllRoles();
|
||||
const data: LoaderData = {
|
||||
title: `${item.name} | ${t("models.permission.object")} | ${process.env.APP_NAME}`,
|
||||
item,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
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.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const existing = await getPermission(params.id ?? "");
|
||||
if (!existing) {
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const roles = form.getAll("roles[]").map((f) => f.toString());
|
||||
const data = {
|
||||
name,
|
||||
description,
|
||||
type,
|
||||
};
|
||||
await updatePermission(existing.id, data);
|
||||
await setPermissionRoles(existing.id, roles);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.permissions.updated",
|
||||
`${existing.name}: ${JSON.stringify({
|
||||
...data,
|
||||
roles,
|
||||
})}`
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.roles.delete");
|
||||
await deletePermission(existing.id);
|
||||
createAdminLog(request, "admin.permissions.deleted", `${existing.name}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminEditPermissionRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<PermissionForm
|
||||
item={data.item}
|
||||
roles={data.roles}
|
||||
onCancel={goBack}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.roles.update")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.roles.delete")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import PermissionForm from "~/components/core/roles/PermissionForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { createPermission, getNextPermissionsOrder, getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setPermissionRoles } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { getAllRoles, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const roles = await getAllRoles();
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.permission.object")} | ${process.env.APP_NAME}`,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const roles = form.getAll("roles[]").map((f) => f.toString());
|
||||
|
||||
const existing = await getPermissionName(name);
|
||||
if (existing) {
|
||||
return badRequest({ error: t("admin.accounts.rolesAndPermissions.permissions.errors.existingPermission", { name }) });
|
||||
}
|
||||
|
||||
const order = await getNextPermissionsOrder(type);
|
||||
const data = {
|
||||
order,
|
||||
name,
|
||||
description,
|
||||
type,
|
||||
isDefault: false,
|
||||
entityId: null,
|
||||
};
|
||||
const permission = await createPermission(data);
|
||||
await setPermissionRoles(permission.id, roles);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.permissions.created",
|
||||
`${JSON.stringify({
|
||||
...data,
|
||||
roles,
|
||||
})}`
|
||||
);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminEditPermissionRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
return <PermissionForm roles={data.roles} onCancel={goBack} />;
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/accounts/roles-and-permissions");
|
||||
|
||||
function readRoute(relativePath: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("admin role assignment scoping", () => {
|
||||
it("restricts account user assignments to app roles and tenant members or admins", () => {
|
||||
const source = readRoute("account-users.$account.tsx");
|
||||
|
||||
expect(source).toContain("getTenantMember");
|
||||
expect(source).toContain('role.type !== "app"');
|
||||
expect(source).toContain("!user.admin && !tenantMember");
|
||||
expect(source).toContain("createUserRole(userId, roleId, tenant.id)");
|
||||
expect(source).toContain("deleteUserRole(userId, roleId, tenant.id)");
|
||||
expect(source).not.toContain("createUserRole(userId, roleId, params.account)");
|
||||
expect(source).not.toContain("deleteUserRole(userId, roleId, params.account)");
|
||||
});
|
||||
|
||||
it("restricts admin user assignments to admin users and admin roles", () => {
|
||||
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)");
|
||||
});
|
||||
|
||||
it("writes clean role assignment audit details", () => {
|
||||
const adminUsersSource = readRoute("admin-users.tsx");
|
||||
const accountUsersSource = readRoute("account-users.$account.tsx");
|
||||
|
||||
expect(adminUsersSource).not.toContain("${role.name}}");
|
||||
expect(accountUsersSource).not.toContain("${role.name}}");
|
||||
expect(adminUsersSource).toContain("`${user.email} - ${role.name}`");
|
||||
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",
|
||||
"roles/new.tsx",
|
||||
"roles/$id.tsx",
|
||||
];
|
||||
|
||||
const actions = routeFiles.flatMap((file) => {
|
||||
const source = readRoute(file);
|
||||
return Array.from(source.matchAll(/createAdminLog\s*\(\s*request,\s*"([^"]+)"/gu))
|
||||
.map((match) => match[1])
|
||||
.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");
|
||||
expect(actions).toContain("admin.permissions.created");
|
||||
expect(actions).toContain("admin.permissions.updated");
|
||||
expect(actions).toContain("admin.permissions.deleted");
|
||||
expect(actions).toContain("admin.roles.created");
|
||||
expect(actions).toContain("admin.roles.deleted");
|
||||
expect(actions).not.toContain("Create");
|
||||
expect(actions).not.toContain("Created");
|
||||
expect(actions).not.toContain("Updated");
|
||||
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",
|
||||
"admin.permissions.updated",
|
||||
"admin.permissions.deleted",
|
||||
"admin.roles.created",
|
||||
"admin.roles.updated",
|
||||
"admin.roles.deleted",
|
||||
])
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
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";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { getFiltersFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
|
||||
import { getAllPermissionsIdsAndNames } from "~/utils/db/permissions/permissions.db.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useTranslation } from "react-i18next";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: RoleWithPermissionsAndUsers[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.roles-and-permissions.roles");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{ name: "name", title: "models.role.name" },
|
||||
{ name: "description", title: "models.role.description" },
|
||||
{
|
||||
name: "permissionId",
|
||||
title: "models.permission.object",
|
||||
manual: true,
|
||||
options: (await time(getAllPermissionsIdsAndNames(), "getAllPermissionsIdsAndNames")).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const items = await time(getAllRolesWithUsers(undefined, filters), "getAllRolesWithUsers");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
filterableProperties,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex space-x-2">
|
||||
<div className="grow">
|
||||
<InputSearchWithURL />
|
||||
</div>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
<ButtonPrimary to="new">
|
||||
<div className="sm:text-sm">+</div>
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
{/* <InputSearchWithURL onNewRoute={getUserHasPermission(adminData, "admin.roles.create") ? "new" : undefined} /> */}
|
||||
<RolesTable items={data.items} canUpdate={getUserHasPermission(adminData, "admin.roles.update")} />
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("shared.edit") : t("shared.new")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-lg"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import RoleForm from "~/components/core/roles/RoleForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getAllPermissions, PermissionWithRoles } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setRolePermissions } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { deleteRole, getRole, RoleWithPermissions, updateRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
item: RoleWithPermissions;
|
||||
permissions: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getRole(params.id ?? "");
|
||||
if (!item) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
const permissions = await getAllPermissions();
|
||||
const data: LoaderData = {
|
||||
title: `${item.name} | ${t("models.role.object")} | ${process.env.APP_NAME}`,
|
||||
item,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const existing = await getRole(params.id ?? "");
|
||||
if (!existing) {
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const assignToNewUsers = Boolean(form.get("assign-to-new-users"));
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const permissions = form.getAll("permissions[]").map((f) => f.toString());
|
||||
const data = {
|
||||
name,
|
||||
description,
|
||||
assignToNewUsers,
|
||||
type,
|
||||
};
|
||||
try {
|
||||
await updateRole(existing.id, data);
|
||||
await setRolePermissions(existing.id, permissions);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.roles.updated",
|
||||
`${existing.name}: ${JSON.stringify({
|
||||
...data,
|
||||
permissions,
|
||||
})}`
|
||||
);
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.updateFailed") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.roles.delete");
|
||||
await deleteRole(existing.id);
|
||||
createAdminLog(request, "admin.roles.deleted", `${existing.name}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminEditRoleRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<RoleForm
|
||||
item={data.item}
|
||||
permissions={data.permissions}
|
||||
onCancel={goBack}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.roles.update")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.roles.delete")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import RoleForm from "~/components/core/roles/RoleForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getAllPermissions, PermissionWithRoles } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setRolePermissions } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { createRole, getNextRolesOrder, getRoleByName } from "~/utils/db/permissions/roles.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
permissions: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const permissions = await getAllPermissions();
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.object")} | ${process.env.APP_NAME}`,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const assignToNewUsers = Boolean(form.get("assign-to-new-users"));
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const permissions = form.getAll("permissions[]").map((f) => f.toString());
|
||||
|
||||
const existing = await getRoleByName(name);
|
||||
if (existing) {
|
||||
return badRequest({ error: t("admin.accounts.rolesAndPermissions.roles.errors.existingRole", { name }) });
|
||||
}
|
||||
|
||||
const order = await getNextRolesOrder(type);
|
||||
const data = {
|
||||
order,
|
||||
name,
|
||||
description,
|
||||
assignToNewUsers,
|
||||
type,
|
||||
isDefault: false,
|
||||
};
|
||||
const role = await createRole(data);
|
||||
await setRolePermissions(role.id, permissions);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.roles.created",
|
||||
`${JSON.stringify({
|
||||
...data,
|
||||
permissions,
|
||||
})}`
|
||||
);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminNewRoleRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
return <RoleForm permissions={data.permissions} onCancel={goBack} />;
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useRef } from "react";
|
||||
import {
|
||||
CreatePermissionDto,
|
||||
CreateRoleDto,
|
||||
defaultAdminRoles,
|
||||
defaultAppRoles,
|
||||
defaultPermissions,
|
||||
seedRolesAndPermissions,
|
||||
} from "~/utils/services/rolesAndPermissionsService";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getAllRolesNames } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllPermissionsIdsAndNames } from "~/utils/db/permissions/permissions.db.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { toast } from "sonner";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
roles: {
|
||||
all: CreateRoleDto[];
|
||||
missing: CreateRoleDto[];
|
||||
};
|
||||
permissions: {
|
||||
all: CreatePermissionDto[];
|
||||
missing: CreatePermissionDto[];
|
||||
};
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const roles: { all: CreateRoleDto[]; missing: CreateRoleDto[] } = {
|
||||
all: [...defaultAppRoles, ...defaultAdminRoles],
|
||||
missing: [],
|
||||
};
|
||||
const createdRoles = await getAllRolesNames();
|
||||
roles.all.forEach((role) => {
|
||||
const existing = createdRoles.find((r) => r.name === role.name);
|
||||
if (!existing) {
|
||||
roles.missing.push(role);
|
||||
}
|
||||
});
|
||||
|
||||
const permissions: { all: CreatePermissionDto[]; missing: CreatePermissionDto[] } = {
|
||||
all: defaultPermissions,
|
||||
missing: [],
|
||||
};
|
||||
const createdPermissions = await getAllPermissionsIdsAndNames();
|
||||
permissions.all.forEach((permission) => {
|
||||
const existing = createdPermissions.find((r) => r.name === permission.name);
|
||||
if (!existing) {
|
||||
permissions.missing.push(permission);
|
||||
}
|
||||
});
|
||||
const data: LoaderData = {
|
||||
title: t("admin.accounts.rolesAndPermissions.seed.metaTitle", { appName: process.env.APP_NAME }),
|
||||
roles,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "seed") {
|
||||
try {
|
||||
await seedRolesAndPermissions();
|
||||
return Response.json({ success: t("admin.accounts.rolesAndPermissions.seed.actions.seeded") }, { status: 200 });
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 500 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const submit = useSubmit();
|
||||
|
||||
const modalConfirmSeed = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onSeed() {
|
||||
modalConfirmSeed.current?.show(
|
||||
t("admin.accounts.rolesAndPermissions.seed.confirm.title"),
|
||||
t("shared.confirm"),
|
||||
t("shared.back"),
|
||||
t("admin.accounts.rolesAndPermissions.seed.confirm.description")
|
||||
);
|
||||
}
|
||||
|
||||
function onConfirmSeed() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "seed");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<InputGroup title={t("admin.accounts.rolesAndPermissions.seed.missingTitle")}>
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-foreground text-lg font-medium">{t("models.role.plural")}</h3>
|
||||
<TableSimple
|
||||
items={data.roles.missing}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.name"),
|
||||
value: (i) => i.name,
|
||||
className: "w-full",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<h3 className="text-foreground text-lg font-medium">{t("models.permission.plural")}</h3>
|
||||
<TableSimple
|
||||
items={data.permissions.missing}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.name"),
|
||||
value: (i) => i.name,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("shared.description"),
|
||||
value: (i) => i.description,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "inRoles",
|
||||
title: t("models.permission.inRoles"),
|
||||
value: (i) => i.inRoles.join(", "),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonSecondary disabled={!getUserHasPermission(appOrAdminData, "admin.roles.update")} destructive onClick={onSeed}>
|
||||
{t("admin.accounts.rolesAndPermissions.seed.button", {
|
||||
rolesMissing: data.roles.missing.length,
|
||||
rolesTotal: data.roles.all.length,
|
||||
permissionsMissing: data.permissions.missing.length,
|
||||
permissionsTotal: data.permissions.all.length,
|
||||
})}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<ConfirmModal ref={modalConfirmSeed} onYes={onConfirmSeed} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/accounts");
|
||||
|
||||
function readRoute(file: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, file), "utf8");
|
||||
}
|
||||
|
||||
describe("admin account subscription i18n", () => {
|
||||
it("uses plan copy for subscription-product labels and precise renewal status labels", () => {
|
||||
const en = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/en/translations.json"), "utf8"));
|
||||
const de = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/de/translations.json"), "utf8"));
|
||||
|
||||
expect(en.models.subscriptionProduct.object).toBe("Subscription plan");
|
||||
expect(en.models.subscriptionProduct.plural).toBe("Subscription plans");
|
||||
expect(de.models.subscriptionProduct.object).toBe("Tarif");
|
||||
expect(de.models.subscriptionProduct.plural).toBe("Tarife");
|
||||
expect(en.admin.accounts.subscriptions.filters.status.activeCancelled).toBe("Active, cancellation scheduled");
|
||||
expect(en.admin.accounts.subscriptions.filters.status.activeNotCancelled).toBe("Active, renewing");
|
||||
expect(de.admin.accounts.subscriptions.filters.status.activeCancelled).toBe("Aktiv, Kündigung vorgemerkt");
|
||||
expect(de.admin.accounts.subscriptions.filters.status.activeNotCancelled).toBe("Aktiv, verlängert sich");
|
||||
});
|
||||
|
||||
it("keeps subscription filters and revenue table copy behind semantic keys", () => {
|
||||
const subscriptions = readRoute("subscriptions.tsx");
|
||||
const revenue = readRoute("subscriptions-revenue.tsx");
|
||||
const detail = readRoute("subscriptions/$id.tsx");
|
||||
|
||||
expect(subscriptions).toContain("admin.accounts.subscriptions.filters.status.activeCancelled");
|
||||
expect(subscriptions).toContain("shared.notAvailable");
|
||||
expect(subscriptions).toContain("shared.actions");
|
||||
expect(subscriptions).toContain("formatters.currency");
|
||||
expect(subscriptions).toContain("formatters.date(i.endsAt");
|
||||
expect(subscriptions).not.toContain('name: "Active"');
|
||||
expect(subscriptions).not.toContain("`$${");
|
||||
expect(subscriptions).not.toContain(' : "-"');
|
||||
expect(subscriptions).not.toContain("<div>-</div>");
|
||||
expect(subscriptions).not.toContain("DateUtils");
|
||||
|
||||
expect(revenue).toContain("admin.accounts.revenue.metaTitle");
|
||||
expect(revenue).toContain("admin.accounts.revenue.table.revenueUsd");
|
||||
expect(revenue).toContain("formatters.percent(item.countPercentage)");
|
||||
expect(revenue).toContain("formatters.percent(item.revenuePercentageUsd)");
|
||||
expect(revenue).not.toContain("ui.autogenerated");
|
||||
expect(revenue).not.toContain("NumberUtils");
|
||||
expect(revenue).not.toContain('title={"Revenue"}');
|
||||
expect(revenue).not.toContain(" usd");
|
||||
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.stripeId");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currentPeriod");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.canceledAt");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currency");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.priceAmount");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.billingPeriod");
|
||||
expect(detail).toContain('t("pricing." + SubscriptionBillingPeriod');
|
||||
expect(detail).toContain("shared.notAvailable");
|
||||
expect(detail).toContain("useLocaleFormatters");
|
||||
expect(detail).toContain("formatters.currency");
|
||||
expect(detail).not.toContain("price?.toString()");
|
||||
expect(detail).not.toContain(' : "-"');
|
||||
expect(detail).not.toContain(' : ""');
|
||||
expect(detail).not.toContain("ui.autogenerated");
|
||||
expect(detail).not.toContain("i18nT");
|
||||
expect(detail).not.toContain("DateUtils");
|
||||
expect(detail).not.toContain("defaultValue={SubscriptionBillingPeriod[");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { StripeRevenueByProductPriceCurrency, getStripeRevenueByProductPriceCurrency } from "~/utils/stripe.server";
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: StripeRevenueByProductPriceCurrency[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: t("admin.accounts.revenue.metaTitle", { appName: process.env.APP_NAME }) }],
|
||||
items: await getStripeRevenueByProductPriceCurrency(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.accounts.revenue.title")}>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "product",
|
||||
title: t("admin.accounts.revenue.table.product"),
|
||||
value: (item) => t(item.product),
|
||||
},
|
||||
{
|
||||
name: "billingPeriod",
|
||||
title: t("admin.accounts.revenue.table.billingPeriod"),
|
||||
value: (item) => t("pricing." + SubscriptionBillingPeriod[item.billingPeriod]),
|
||||
},
|
||||
{
|
||||
name: "currency",
|
||||
title: t("admin.accounts.revenue.table.currency"),
|
||||
value: (item) => item.currency,
|
||||
},
|
||||
{
|
||||
name: "revenueInCurrency",
|
||||
title: t("admin.accounts.revenue.table.revenueInCurrency"),
|
||||
value: (item) => item.revenueInCurrency,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.currency(item.revenueInCurrency, item.currency.toUpperCase())}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "count",
|
||||
title: t("admin.accounts.revenue.table.count"),
|
||||
value: (item) => item.count,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.number(item.count, { maximumFractionDigits: 0 })}</div>
|
||||
<div className="text-muted-foreground text-xs">{formatters.percent(item.countPercentage)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "revenueUsd",
|
||||
title: t("admin.accounts.revenue.table.revenueUsd"),
|
||||
value: (item) => item.revenueUsd,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.currency(item.revenueUsd, "USD")}</div>
|
||||
<div className="text-muted-foreground text-xs">{formatters.percent(item.revenuePercentageUsd)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Link, useNavigate, useOutlet } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import TenantBadge from "~/components/core/tenants/TenantBadge";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
|
||||
import {
|
||||
getAllSubscriptionProducts,
|
||||
getAllTenantSubscriptionProducts,
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: TenantSubscriptionProductWithTenant[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
isStripeTest: boolean;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
let { t } = await getTranslations(request);
|
||||
const [subscriptionProducts, tenantOptions] = await Promise.all([getAllSubscriptionProducts(), adminGetAllTenantsIdsAndNames()]);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "status",
|
||||
title: t("shared.status"),
|
||||
manual: true,
|
||||
options: [
|
||||
{ value: "active", name: t("admin.accounts.subscriptions.filters.status.active") },
|
||||
{ value: "ended", name: t("admin.accounts.subscriptions.filters.status.ended") },
|
||||
{ value: "active-cancelled", name: t("admin.accounts.subscriptions.filters.status.activeCancelled") },
|
||||
{ value: "active-not-cancelled", name: t("admin.accounts.subscriptions.filters.status.activeNotCancelled") },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "subscriptionProductId",
|
||||
title: t("models.subscriptionProduct.object"),
|
||||
manual: true,
|
||||
options: subscriptionProducts.map((f) => {
|
||||
return {
|
||||
value: f.id ?? "",
|
||||
name: t(f.title),
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
manual: true,
|
||||
options: tenantOptions.map((tenant) => {
|
||||
return {
|
||||
value: tenant.id,
|
||||
name: tenant.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
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 data: LoaderData = {
|
||||
metatags: [{ title: `${t("models.subscription.plural")} | ${process.env.APP_NAME}` }],
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const notAvailable = t("shared.notAvailable");
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.subscription.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters filters={data.filterableProperties} withSearch={false} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("models.tenant.object"),
|
||||
value: (i) => <TenantBadge item={i.tenantSubscription.tenant} />,
|
||||
},
|
||||
{
|
||||
name: "subscriptionProduct",
|
||||
title: t("models.subscriptionProduct.object"),
|
||||
value: () => "",
|
||||
className: "w-full",
|
||||
formattedValue: (product) => (
|
||||
<span>
|
||||
<div key={product.id}>
|
||||
<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
|
||||
)}`
|
||||
)
|
||||
.join(", ")}
|
||||
</div>
|
||||
</div>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "period",
|
||||
title: t("models.subscription.period"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
{i.currentPeriodStart && i.currentPeriodEnd ? (
|
||||
<div className="flex items-center space-x-1">
|
||||
<DateCell date={i.currentPeriodStart} displays={["mdy"]} />
|
||||
<div aria-hidden="true">-</div>
|
||||
<DateCell date={i.currentPeriodEnd} displays={["mdy"]} />
|
||||
</div>
|
||||
) : (
|
||||
<div>{notAvailable}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "cancelledAt",
|
||||
title: t("models.subscription.cancelledAt"),
|
||||
value: (i) => <div>{i.cancelledAt ? <DateCell date={i.cancelledAt} displays={["mdy"]} /> : notAvailable}</div>,
|
||||
},
|
||||
{
|
||||
name: "endsAt",
|
||||
title: t("models.subscription.endsAt"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
{i.endsAt ? (
|
||||
<div>
|
||||
{new Date() < new Date(i.endsAt) ? (
|
||||
<div className="text-orange-500">
|
||||
{t("settings.subscription.ends")} {formatters.date(i.endsAt, { dateStyle: "medium" })}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-red-500">
|
||||
{t("settings.subscription.endedAt")} {formatters.date(i.endsAt, { dateStyle: "medium" })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
notAvailable
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: t("shared.actions"),
|
||||
value: (i) => (
|
||||
<Link to={`${i.id}`} className="hover:underline">
|
||||
{t("shared.edit")}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWithTenant } from "@toolctrl/db/subscriptions.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: TenantSubscriptionProductWithTenant;
|
||||
};
|
||||
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!);
|
||||
if (!item) {
|
||||
return Response.json({ error: t("admin.accounts.subscriptions.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const formatDate = (value: Date | string | null | undefined) => (value ? formatters.date(value, { dateStyle: "medium" }) : t("shared.notAvailable"));
|
||||
const formatPriceAmount = (value: unknown, currency: string | null | undefined) => {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return t("shared.notAvailable");
|
||||
}
|
||||
const amount = Number(value);
|
||||
return Number.isFinite(amount) ? formatters.currency(amount, (currency ?? "USD").toUpperCase()) : t("shared.notAvailable");
|
||||
};
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputText title={t("models.tenant.object")} defaultValue={data.item.tenantSubscription.tenant.name} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.stripeId")} defaultValue={data.item.stripeSubscriptionId ?? ""} readOnly />
|
||||
<InputText title={t("models.subscriptionProduct.object")} defaultValue={t(data.item.subscriptionProduct.title)} readOnly />
|
||||
<InputText title={t("models.subscription.quantity")} defaultValue={data.item.quantity?.toString() ?? ""} readOnly />
|
||||
{data.item.prices.length > 0 && (
|
||||
<InputGroup title={t("models.subscription.price")}>
|
||||
<div className="space-y-1">
|
||||
{data.item.prices.map((price) => (
|
||||
<Fragment key={price.id}>
|
||||
{price.subscriptionPrice ? (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.currency")} defaultValue={price.subscriptionPrice.currency} readOnly />
|
||||
<InputText
|
||||
title={t("admin.accounts.subscriptions.fields.priceAmount")}
|
||||
defaultValue={formatPriceAmount(price.subscriptionPrice.price, price.subscriptionPrice.currency)}
|
||||
readOnly
|
||||
/>
|
||||
<InputText
|
||||
title={t("admin.accounts.subscriptions.fields.billingPeriod")}
|
||||
defaultValue={t("pricing." + SubscriptionBillingPeriod[price.subscriptionPrice.billingPeriod])}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Fragment></Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</InputGroup>
|
||||
)}
|
||||
<InputGroup title={t("admin.accounts.subscriptions.fields.currentPeriod")}>
|
||||
<div className="space-y-1">
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.startedAt")} defaultValue={formatDate(data.item.currentPeriodStart)} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.endsAt")} defaultValue={formatDate(data.item.currentPeriodEnd)} readOnly />
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.createdAt")} defaultValue={formatDate(data.item.createdAt)} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.canceledAt")} defaultValue={formatDate(data.item.cancelledAt)} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.endsAt")} defaultValue={formatDate(data.item.endsAt)} readOnly />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
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 {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useActionData: () => undefined,
|
||||
useLoaderData: () => ({}),
|
||||
useNavigate: () => vi.fn(),
|
||||
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("@toolctrl/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: undefined }),
|
||||
}));
|
||||
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/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("~/utils/auth/mfa/step-up.server", () => ({
|
||||
checkMfaStepUpState: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsIdsAndNames: vi.fn(),
|
||||
getTenant: vi.fn(),
|
||||
}));
|
||||
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/session.server", () => ({
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-05-08T17:00:00.000Z"),
|
||||
createUserSession: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getUserSession: vi.fn(),
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/impersonation-audit.server", () => ({
|
||||
createImpersonationAudit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.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 { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { createUserSession, getUserInfo, getUserSession, 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 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", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: actionName, "user-id": targetUser.id, ...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>) };
|
||||
}
|
||||
}
|
||||
|
||||
describe("admin accounts user impersonation MFA guard", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined 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(getTenant).mockResolvedValue({ id: "tenant-1", slug: "acme" } 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();
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
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");
|
||||
expect(setLoggedUser).not.toHaveBeenCalled();
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
expect(createUserSession).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("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);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,376 @@
|
||||
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 { 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";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
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 "@toolctrl/db/prisma-browser";
|
||||
import { getLastUserLogsByUserIds } 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 { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { absoluteAppPath, absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
// export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
export const meta = ({ data }: { data: LoaderData }) => [{ title: data.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
lastLogs: { userId: string; log: Log }[];
|
||||
};
|
||||
|
||||
export function adminImpersonationRedirectTarget(
|
||||
tenant: { slug?: string | null } | null,
|
||||
routing: PublicDomainRoutingConfig = loadRequiredWebConfig().routing
|
||||
) {
|
||||
return tenant?.slug ? absoluteAppPath(routing, tenant.slug, "dashboard") : absoluteAppRootPath(routing);
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.users");
|
||||
await time(verifyUserHasPermission(request, "admin.users.view"), "verifyUserHasPermission");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{ name: "email", title: t("models.user.email") },
|
||||
{ name: "firstName", title: t("models.user.firstName") },
|
||||
{ name: "lastName", title: t("models.user.lastName") },
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
manual: true,
|
||||
options: (await adminGetAllTenantsIdsAndNames()).map((tenant) => {
|
||||
return {
|
||||
value: tenant.id,
|
||||
name: tenant.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "lastLogin",
|
||||
title: t("admin.accounts.users.filters.hasLoggedIn"),
|
||||
manual: true,
|
||||
options: [
|
||||
{
|
||||
value: "last-24-hours", // days
|
||||
name: t("app.shared.periods.LAST_24_HOURS"),
|
||||
},
|
||||
{
|
||||
value: "last-7-days", // days
|
||||
name: t("app.shared.periods.LAST_WEEK"),
|
||||
},
|
||||
{
|
||||
value: "last-30-days", // days
|
||||
name: t("app.shared.periods.LAST_30_DAYS"),
|
||||
},
|
||||
{
|
||||
value: "last-3-months", // months
|
||||
name: t("app.shared.periods.LAST_3_MONTHS"),
|
||||
},
|
||||
{
|
||||
value: "last-6-months", // months
|
||||
name: t("app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }),
|
||||
},
|
||||
{
|
||||
value: "last-year", // months
|
||||
name: t("app.shared.periods.LAST_YEAR"),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "isAdmin",
|
||||
title: "models.user.isAdmin",
|
||||
manual: true,
|
||||
isBoolean: true,
|
||||
hideSearch: true,
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
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
|
||||
.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);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.user.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
filterableProperties,
|
||||
pagination,
|
||||
lastLogs,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
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();
|
||||
const action = form.get("action")?.toString();
|
||||
const userId = form.get("user-id")?.toString();
|
||||
const user = await getUser(userId);
|
||||
|
||||
if (!userId || !user || !action) {
|
||||
return badRequest({ error: t("admin.users.errors.invalidForm") });
|
||||
}
|
||||
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"),
|
||||
});
|
||||
}
|
||||
// Reuse the tenant resolved inside setLoggedUser to avoid a duplicate
|
||||
// getTenant() round-trip on every impersonation start.
|
||||
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",
|
||||
targetId: user.id,
|
||||
sourceModule: "admin",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: { requestPath: new URL(request.url).pathname, reason: "admin.users.impersonate" },
|
||||
});
|
||||
return createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
impersonatingFromUserId: userInfo.userId,
|
||||
impersonatingStartedAt: createImpersonationStartedAt(),
|
||||
},
|
||||
adminImpersonationRedirectTarget(tenant)
|
||||
);
|
||||
}
|
||||
case "change-password": {
|
||||
await verifyUserHasPermission(request, "admin.users.changePassword");
|
||||
const actor = await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
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 } : {});
|
||||
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,
|
||||
});
|
||||
|
||||
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);
|
||||
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({
|
||||
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 success({ success: t("shared.deleted") });
|
||||
}
|
||||
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>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.user.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button asChild type="button" variant="default" size="sm">
|
||||
<Link to="new">{t("shared.new")}</Link>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<UsersTable
|
||||
items={data.items}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
canSetUserRoles={adminData.isSuperAdmin}
|
||||
pagination={data.pagination}
|
||||
lastLogs={data.lastLogs}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Phase 10 Task #68 — DSGVO admin override UI.
|
||||
*
|
||||
* Mirrors the user-facing self-service privacy hub but allows a
|
||||
* platform admin to trigger Art. 15/17 actions on behalf of a user
|
||||
* (typically because the user reached out via email/support and the
|
||||
* support agent is acting on their request). Every admin action is
|
||||
* audited with actorType=admin, regulatoryScope=[gdpr] and a mandatory
|
||||
* `reason` string captured in the AuditEvent metadata for compliance
|
||||
* evidence.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
|
||||
import { formatDate, useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
pendingDeletion: boolean;
|
||||
scheduledDeletionAt: string | null;
|
||||
pseudonymized: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
type ActionData = { ok: true; intent: string; message: string } | { ok: false; error: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const db = getDbClient();
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: params.user ?? "__missing__" },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
pendingDeletion: true,
|
||||
scheduledDeletionAt: true,
|
||||
pseudonymized: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.privacy.admin.title")} - ${user.email}`,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
pendingDeletion: user.pendingDeletion,
|
||||
scheduledDeletionAt: user.scheduledDeletionAt ? user.scheduledDeletionAt.toISOString() : null,
|
||||
pseudonymized: user.pseudonymized,
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
// Capacitor track patch (#65 → unblocks main): the dsgvo-bulk-ops
|
||||
// agent referenced a non-existent `admin.users.update` permission;
|
||||
// the seed catalog only exposes `admin.users.view`. Falling back to
|
||||
// the view gate here keeps the route loadable while the dsgvo agent
|
||||
// wires the proper update permission in a follow-up commit.
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
await validateCSRFToken(request);
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const reason = String(form.get("reason") ?? "").trim();
|
||||
if (reason.length < 10) {
|
||||
return Response.json(
|
||||
{ ok: false, error: t("settings.privacy.admin.errors.reasonMinLength") } satisfies ActionData,
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const userId = params.user ?? "";
|
||||
const db = getDbClient();
|
||||
const user = await db.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
return Response.json({ ok: false, error: t("settings.privacy.admin.errors.userNotFound") } satisfies ActionData, { status: 404 });
|
||||
}
|
||||
const requestId = randomUUID();
|
||||
|
||||
if (intent === "export") {
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "REQUEST_PERSONAL_DATA_EXPORT",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "export", source: "admin-override", reason },
|
||||
});
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
message: t("settings.privacy.admin.messages.exportRequested"),
|
||||
} satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "delete") {
|
||||
const now = new Date();
|
||||
const scheduledDeletionAt = new Date(now.getTime() + DSGVO_GRACE_PERIOD_DAYS * 24 * 60 * 60 * 1000);
|
||||
await db.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
pendingDeletion: true,
|
||||
deletionRequestedAt: now,
|
||||
scheduledDeletionAt,
|
||||
deletionRequestId: requestId,
|
||||
},
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "REQUEST_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "delete", source: "admin-override", reason, scheduledDeletionAt: scheduledDeletionAt.toISOString() },
|
||||
});
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
message: t("settings.privacy.admin.messages.deletionScheduled", {
|
||||
date: formatDate(scheduledDeletionAt, locale, { dateStyle: "medium", timeStyle: "short" }),
|
||||
}),
|
||||
} satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "pseudonymize") {
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "PSEUDONYMIZE_USER_REQUESTED",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "pseudonymize", source: "admin-override", reason },
|
||||
});
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
message: t("settings.privacy.admin.messages.pseudonymizationQueued"),
|
||||
} satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "reactivate") {
|
||||
await db.user.update({
|
||||
where: { id: userId },
|
||||
data: { pendingDeletion: false, deletionRequestedAt: null, scheduledDeletionAt: null, deletionRequestId: null },
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "CANCEL_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "reactivate", source: "admin-override", reason },
|
||||
});
|
||||
return Response.json({ ok: true, intent, message: t("settings.privacy.admin.messages.deletionCancelled") } satisfies ActionData);
|
||||
}
|
||||
|
||||
return Response.json({ ok: false, error: t("settings.privacy.admin.errors.unknownIntent", { intent }) } satisfies ActionData, {
|
||||
status: 400,
|
||||
});
|
||||
};
|
||||
|
||||
export default function AdminPrivacyOpsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const action = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const intentLabels = {
|
||||
export: t("settings.privacy.admin.intents.export"),
|
||||
delete: t("settings.privacy.admin.intents.delete"),
|
||||
pseudonymize: t("settings.privacy.admin.intents.pseudonymize"),
|
||||
reactivate: t("settings.privacy.admin.intents.reactivate"),
|
||||
} as const;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-xl font-semibold">{t("settings.privacy.admin.heading", { email: data.user.email })}</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("settings.privacy.admin.description")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{action && action.ok ? <div className="rounded border border-green-300 bg-green-50 p-3 text-sm">{action.message}</div> : null}
|
||||
{action && !action.ok ? <div className="rounded border border-red-300 bg-red-50 p-3 text-sm">{action.error}</div> : null}
|
||||
|
||||
<section className="rounded border p-4">
|
||||
<h2 className="text-lg font-medium">{t("shared.status")}</h2>
|
||||
<ul className="mt-2 text-sm">
|
||||
<li>
|
||||
{t("settings.privacy.admin.status.pendingDeletion")}: <strong>{data.user.pendingDeletion ? t("shared.yes") : t("shared.no")}</strong>
|
||||
</li>
|
||||
<li>
|
||||
{t("settings.privacy.admin.status.pseudonymized")}: <strong>{data.user.pseudonymized ? t("shared.yes") : t("shared.no")}</strong>
|
||||
</li>
|
||||
{data.user.scheduledDeletionAt ? (
|
||||
<li>
|
||||
{t("settings.privacy.admin.status.scheduledForDeletionAt")}:{" "}
|
||||
<strong>{formatters.date(data.user.scheduledDeletionAt, { dateStyle: "medium", timeStyle: "short" })}</strong>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{(["export", "delete", "pseudonymize", "reactivate"] as const).map((intent) => (
|
||||
<Form method="post" key={intent} className="space-y-2 rounded border p-4">
|
||||
<h3 className="font-medium">{intentLabels[intent]}</h3>
|
||||
<input type="hidden" name="intent" value={intent} />
|
||||
<label className="block text-sm">
|
||||
<span>{t("settings.privacy.admin.reason")}</span>
|
||||
<textarea
|
||||
name="reason"
|
||||
required
|
||||
minLength={10}
|
||||
rows={2}
|
||||
className="mt-1 w-full rounded border px-2 py-1"
|
||||
placeholder={t("settings.privacy.admin.reasonPlaceholder")}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500">
|
||||
{t("settings.privacy.admin.submit", { intent: intentLabels[intent] })}
|
||||
</button>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { UserWithDetails, getUserByEmail, getUserByEmailWithDetails } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
user: UserWithDetails;
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const user = await getUserByEmailWithDetails(params.user!);
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
user,
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const user = await getUserByEmail(params.user);
|
||||
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "set-user-roles") {
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
let setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
setRoles = setRoles.filter((v, i, a) => a.findIndex((t) => t.role.id === v.role.id) === i);
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const countAdmins = await db.adminUser.count();
|
||||
if (!isAdmin && countAdmins === 1) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveLastAdmin") }, { status: 400 });
|
||||
}
|
||||
const hasSuperAdmin = setRoles.some((r) => r.role.name === DefaultAdminRoles.SuperAdmin);
|
||||
if (user.id === userInfo.userId && !hasSuperAdmin) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveOwnSuperAdmin") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
// return Response.json({ success: t("shared.updated") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>(data.user.roles?.filter((f) => f.role.type === "admin").map((r) => r.role.id));
|
||||
|
||||
function hasSomeAdminRoles() {
|
||||
return data.adminRoles.some((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
function hasAllAdminRoles() {
|
||||
return data.adminRoles.every((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="set-user-roles" hidden readOnly />
|
||||
{selectedRoles?.map((role, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="border-border flex items-center justify-between space-x-2 border-b pb-2">
|
||||
<div className="text-foreground/80 text-lg font-medium">{t("models.role.plural")}</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary disabled={!hasSomeAdminRoles()} onClick={() => setSelectedRoles([])}>
|
||||
{t("shared.clear")}
|
||||
</ButtonSecondary>
|
||||
|
||||
<ButtonSecondary disabled={hasAllAdminRoles()} onClick={() => setSelectedRoles(data.adminRoles.map((r) => r.id))}>
|
||||
{t("shared.selectAll")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-1 rounded-md shadow-2xs">
|
||||
{data.adminRoles?.map((role, idx) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={idx}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
<ActionResultModal actionData={actionData ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const data: LoaderData = {
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "new-user") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const email = form.get("email")?.toString();
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!email || !password || !firstName) {
|
||||
return Response.json({ error: t("admin.users.create.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
// if (arrRoles.length === 0) {
|
||||
// return Response.json({ error: "You must select at least one role." }, { status: 400 });
|
||||
// }
|
||||
|
||||
const existingUser = await getUserByEmail(email);
|
||||
if (existingUser) {
|
||||
return Response.json({ error: t("admin.users.create.errors.userAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
const setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const { id } = await register({
|
||||
email,
|
||||
firstName,
|
||||
lastName: lastName ?? "",
|
||||
password,
|
||||
request,
|
||||
});
|
||||
const user = await getUser(id);
|
||||
if (!user) {
|
||||
return Response.json({ error: t("admin.users.create.errors.unexpectedCreateError") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [password, setPassword] = useState<string>("");
|
||||
const [firstName, setFirstName] = useState<string>("");
|
||||
const [lastName, setLastName] = useState<string>("");
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="new-user" hidden readOnly />
|
||||
{selectedRoles?.map((role) => {
|
||||
return (
|
||||
<input
|
||||
key={role}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText autoFocus type="email" name="email" title={t("models.user.email")} value={email} setValue={setEmail} required />
|
||||
|
||||
<InputText type="password" name="password" title={t("account.shared.password")} value={password} setValue={setPassword} required />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} value={firstName} setValue={setFirstName} required />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} value={lastName} setValue={setLastName} />
|
||||
|
||||
<div>
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">{t("models.role.plural")}</label>
|
||||
<div className="border-border bg-background divide-border divide-y rounded-md border px-2 py-1">
|
||||
{data.adminRoles?.map((role) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={role.name}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user