Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -0,0 +1,78 @@
|
||||
import { buildApiAdminVM } from "@hivegrid/view-models";
|
||||
import { Link, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getApiAdminSnapshot } from "~/services/admin/api-admin.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { apiTabs } from "./index";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildApiAdminVM>;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.apiAdmin.clients.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildApiAdminVM(await getApiAdminSnapshot({ platformLeadVisibility: null })),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
export default function ApiClientsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.consumers : [];
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.apiAdmin.clients.title")} tabs={apiTabs(t)} fullWidth>
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/40 text-muted-foreground text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left">{t("models.tenant.object")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.apiAdmin.consumers.keys")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.apiAdmin.consumers.activeKeys")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.apiAdmin.consumers.lastKey")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-muted-foreground px-3 py-6 text-center">
|
||||
{t("admin.apiAdmin.clients.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rows.map((row) => (
|
||||
<tr key={row.id} className="border-border hover:bg-muted/30 border-t">
|
||||
<td className="px-3 py-2">
|
||||
<Link className="text-primary font-medium hover:underline" to={adminPath(`accounts/${row.id}`, { mode: "host-aware" })}>
|
||||
{row.name}
|
||||
</Link>
|
||||
<div className="text-muted-foreground text-xs">/{row.slug}</div>
|
||||
</td>
|
||||
<td className="px-3 py-2">{format.number(row.keyCount)}</td>
|
||||
<td className="px-3 py-2">{format.number(row.activeKeyCount)}</td>
|
||||
<td className="text-muted-foreground px-3 py-2">{row.lastKeyCreatedAt ? format.dateTime(row.lastKeyCreatedAt) : t("shared.notSet")}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { buildApiAdminVM } from "@hivegrid/view-models";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getApiAdminSnapshot } from "~/services/admin/api-admin.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { apiTabs } from "./index";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildApiAdminVM>;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.apiAdmin.inbound.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildApiAdminVM(await getApiAdminSnapshot({ platformLeadVisibility: null })),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
export default function ApiInboundRegistrationsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const ready = data.vm.status === "ready" ? data.vm.data.inbound : null;
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.apiAdmin.inbound.title")} tabs={apiTabs(t)} fullWidth>
|
||||
<div className="grid gap-4">
|
||||
<div className="rounded-md border">
|
||||
<div className="border-border border-b p-4">
|
||||
<div className="font-medium">{t("admin.apiAdmin.inbound.registrationsTitle")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.apiAdmin.inbound.registrationsDescription")}</div>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{!ready || ready.recentRegistrations.length === 0 ? (
|
||||
<div className="text-muted-foreground p-4 text-sm">{t("admin.apiAdmin.inbound.emptyRegistrations")}</div>
|
||||
) : (
|
||||
ready.recentRegistrations.map((registration) => (
|
||||
<div key={registration.id} className="flex items-start justify-between gap-3 p-4 text-sm">
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium">{registration.email}</div>
|
||||
<div className="text-muted-foreground mt-1 truncate">{registration.company ?? t("shared.notSet")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs">{format.dateTime(registration.createdAt)}</div>
|
||||
</div>
|
||||
<Badge color={registration.createdTenantId ? "green" : "yellow"} withColorDot>
|
||||
{registration.createdTenantId ? t("admin.apiAdmin.inbound.converted") : t("admin.apiAdmin.inbound.pending")}
|
||||
</Badge>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -1,74 +1,218 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { buildApiAdminVM, type ApiAdminMetricInput, type ApiAdminData } from "@hivegrid/view-models";
|
||||
import { FeatherActivity, FeatherArrowRight, FeatherKey, FeatherRadioTower, FeatherShieldAlert, FeatherUsers } from "@subframe/core";
|
||||
import type React from "react";
|
||||
import { Link, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ApiKeyLogsSummary from "~/modules/api/components/ApiKeyLogsSummary";
|
||||
import { ApiCallSummaryDto } from "~/modules/api/dtos/ApiCallSummaryDto";
|
||||
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getApiAdminSnapshot } from "~/services/admin/api-admin.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { EmptyState } from "~/ui/components/EmptyState";
|
||||
import { StatsCard } from "~/ui/components/StatsCard";
|
||||
import { Table } from "~/ui/components/Table";
|
||||
|
||||
type LoaderData =
|
||||
| { error: string }
|
||||
| {
|
||||
items: ApiCallSummaryDto[];
|
||||
allTenants: { id: string; name: string; slug: string }[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
try {
|
||||
const { items, allTenants, filterableProperties } = await ApiKeyLogService.getSummary({ request, params });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
allTenants,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildApiAdminVM>;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const snapshot = await getApiAdminSnapshot({ platformLeadVisibility: null });
|
||||
return {
|
||||
title: `${t("admin.apiAdmin.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildApiAdminVM(snapshot),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
export default function AdminApiIndexRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{"error" in data ? (
|
||||
<ErrorBanner title={t(data.error)}>
|
||||
<Link to="." className="underline">
|
||||
{t("shared.clickHereToTryAgain")}
|
||||
</Link>
|
||||
</ErrorBanner>
|
||||
) : (
|
||||
<Fragment>
|
||||
<ApiKeyLogsSummary data={data} />
|
||||
</Fragment>
|
||||
)}
|
||||
<EditPageLayout title={t("shared.overview")} tabs={apiTabs(t)} fullWidth>
|
||||
{data.vm.status === "ready" ? <ApiAdminPage data={data.vm.data} /> : <EmptyApiAdmin />}
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function apiTabs(t: (key: string) => string) {
|
||||
return [
|
||||
{ name: t("shared.overview"), routePath: adminPath("api", { mode: "host-aware" }) },
|
||||
{ name: t("models.apiCall.plural"), routePath: adminPath("api/logs", { mode: "host-aware" }) },
|
||||
{ name: t("models.apiKey.plural"), routePath: adminPath("api/keys", { mode: "host-aware" }) },
|
||||
{ name: t("admin.apiAdmin.tabs.clients"), routePath: adminPath("api/clients", { mode: "host-aware" }) },
|
||||
{ name: t("admin.apiAdmin.tabs.inbound"), routePath: adminPath("api/inbound-registrations", { mode: "host-aware" }) },
|
||||
];
|
||||
}
|
||||
|
||||
function ApiAdminPage({ data }: { data: ApiAdminData }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-4">
|
||||
<Card variant="neutral">
|
||||
<div className="flex w-full flex-wrap items-center justify-between gap-3">
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t("admin.apiAdmin.publicApiHint")}</span>
|
||||
{data.hasInboundAttention ? (
|
||||
<BadgeFeedback farbe="subtle-warning">{t("admin.apiAdmin.inboundAttention")}</BadgeFeedback>
|
||||
) : (
|
||||
<BadgeFeedback farbe="subtle-positive">{t("admin.apiAdmin.inboundHealthy")}</BadgeFeedback>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<div className="mobile:grid-cols-1 grid w-full gap-4 md:grid-cols-2 xl:grid-cols-5">
|
||||
{data.metrics.map((metric) => (
|
||||
<MetricCard key={metric.id} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mobile:grid-cols-1 grid w-full gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]">
|
||||
<Card>
|
||||
<div className="flex w-full items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("admin.apiAdmin.consumers.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("admin.apiAdmin.consumers.description")}
|
||||
</span>
|
||||
</div>
|
||||
<Link to={adminPath("api/clients", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("shared.viewAll")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Table
|
||||
header={
|
||||
<Table.HeaderRow>
|
||||
<Table.HeaderCell>{t("models.tenant.object")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("admin.apiAdmin.consumers.keys")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("admin.apiAdmin.consumers.activeKeys")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("admin.apiAdmin.consumers.lastKey")}</Table.HeaderCell>
|
||||
</Table.HeaderRow>
|
||||
}
|
||||
>
|
||||
{data.consumers.slice(0, 8).map((consumer) => (
|
||||
<Table.Row key={consumer.id}>
|
||||
<Table.Cell>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<Link
|
||||
className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate hover:underline"
|
||||
to={adminPath(`accounts/${consumer.id}`, { mode: "host-aware" })}
|
||||
>
|
||||
{consumer.name}
|
||||
</Link>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">/{consumer.slug}</span>
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-primary">{format.number(consumer.keyCount)}</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-primary">
|
||||
{format.number(consumer.activeKeyCount)}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{consumer.lastKeyCreatedAt ? format.dateTime(consumer.lastKeyCreatedAt) : t("shared.notSet")}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
))}
|
||||
</Table>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<div className="flex w-full items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("admin.apiAdmin.inbound.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("admin.apiAdmin.inbound.description")}
|
||||
</span>
|
||||
</div>
|
||||
<Link to={adminPath("api/inbound-registrations", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("shared.viewAll")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="grid w-full grid-cols-3 gap-2">
|
||||
<MiniStat label={t("admin.apiAdmin.inbound.pending")} value={data.inbound.registrationsPending} />
|
||||
<MiniStat label={t("admin.apiAdmin.inbound.newLeads")} value={data.inbound.leadsNew} />
|
||||
<MiniStat label={t("admin.apiAdmin.inbound.qualified")} value={data.inbound.leadsQualified} />
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{data.inbound.recentLeads.slice(0, 5).map((lead) => (
|
||||
<Link
|
||||
key={lead.id}
|
||||
to={adminPath(`leads/${lead.id}`, { mode: "host-aware" })}
|
||||
className="border-border-default bg-surface-neutral-primary hover:bg-surface-neutral-secondary/60 flex w-full flex-col items-start rounded-md border border-solid px-4 py-3 transition-colors"
|
||||
>
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">
|
||||
{lead.email ?? lead.company ?? t("shared.notSet")}
|
||||
</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full truncate">
|
||||
{[lead.company, lead.source, t(`admin.platformLeads.status.${lead.status}`)].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ metric }: { metric: ApiAdminMetricInput }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<StatsCard
|
||||
label={t(metric.labelKey)}
|
||||
value={format.number(metric.value)}
|
||||
trend={metric.tone === "success" ? "positive" : metric.tone === "danger" || metric.tone === "warning" ? "negative" : "neutral"}
|
||||
percentage=""
|
||||
comparisonText={t(metric.detailKey)}
|
||||
icon={metricIcon(metric.id)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MiniStat({ label, value }: { label: string; value: number }) {
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<div className="border-border-default bg-surface-neutral-primary flex flex-col items-center rounded-md border border-solid px-3 py-3">
|
||||
<span className="text-subtitle-0 font-subtitle-0 text-text-neutral-primary">{format.number(value)}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyApiAdmin() {
|
||||
const { t } = useTranslation();
|
||||
return <EmptyState outlined title={t("admin.apiAdmin.empty.title")} body={t("admin.apiAdmin.empty.body")} />;
|
||||
}
|
||||
|
||||
function metricIcon(id: string): React.ReactNode {
|
||||
if (id === "keys") return <FeatherKey />;
|
||||
if (id === "activeKeys") return <FeatherShieldAlert />;
|
||||
if (id === "expiredKeys") return <FeatherActivity />;
|
||||
if (id === "failedLogs") return <FeatherRadioTower />;
|
||||
return <FeatherUsers />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, getAllApiKeys } from "~/utils/db/apiKeys.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { apiTabs } from "./index";
|
||||
|
||||
type LoaderData = {
|
||||
apiKeys: RedactedApiKeyWithDetails[];
|
||||
@@ -27,28 +27,8 @@ export default function AdminApiKeysRoute() {
|
||||
const adminData = useAdminData();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
title={t("models.apiKey.plural")}
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ApiKeysTable
|
||||
canCreate={getUserHasPermission(adminData, "admin.apiKeys.create")}
|
||||
items={data.apiKeys}
|
||||
withTenant={true}
|
||||
/>
|
||||
<EditPageLayout title={t("models.apiKey.plural")} tabs={apiTabs(t)} fullWidth>
|
||||
<ApiKeysTable canCreate={getUserHasPermission(adminData, "admin.apiKeys.create")} items={data.apiKeys} withTenant={true} />
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
|
||||
+57
-49
@@ -1,4 +1,5 @@
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
@@ -7,7 +8,7 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, adminGetApiKeyById, deleteApiKey, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
@@ -18,7 +19,7 @@ import { ApiKeyUpdatedDto } from "~/modules/events/dtos/ApiKeyUpdatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
tenants: Pick<Tenant, "id" | "name">[];
|
||||
item: RedactedApiKeyWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -27,7 +28,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!item) {
|
||||
return redirect(adminPath("api", { mode: "host-aware" }));
|
||||
}
|
||||
const tenants = await adminGetAllTenants();
|
||||
const tenants = await adminGetAllTenantsIdsAndNames();
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
tenants,
|
||||
@@ -60,58 +61,65 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
expirationDate = new Date(expires);
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.filter((f) => f.id !== existing.id && f.alias === alias).length > 0) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
if (tenantId !== existing.tenantId) {
|
||||
return badRequest({ error: t("models.apiKey.errors.tenantChangeNotAllowed") });
|
||||
}
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const active = Boolean(form.get("active"));
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
await runWithRlsContext({ tenantId }, async () => {
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.some((item) => item.id !== existing.id && item.alias === alias)) {
|
||||
throw badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
},
|
||||
old: {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
});
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
},
|
||||
old: {
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.saved")}`);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await runWithRlsContext({ tenantId: existing.tenantId }, async () => {
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.deleted")}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenantsIdsAndNames: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/utils/db/apiKeys.db.server", () => ({
|
||||
adminGetApiKeyById: vi.fn(),
|
||||
createApiKey: vi.fn(),
|
||||
deleteApiKey: vi.fn(),
|
||||
getApiKeyByAlias: vi.fn(),
|
||||
getApiKeys: vi.fn(),
|
||||
updateApiKey: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ createAdminLog: vi.fn() }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ adminPath: (path = "") => `/admin/${path}` }));
|
||||
vi.mock("~/components/core/apiKeys/ApiKeyCreatedModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/apiKeys/ApiKeyForm", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/OpenModal", () => ({ default: ({ children }: { children: React.ReactNode }) => children }));
|
||||
vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: () => true }));
|
||||
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetApiKeyById, createApiKey, deleteApiKey, getApiKeyByAlias, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action as createAction } from "./new";
|
||||
import { action as editAction } from "./$id";
|
||||
|
||||
const operator = { id: "operator_1", email: "operator@example.test" };
|
||||
const tenants = [
|
||||
{ id: "tenant_a", name: "Tenant A", slug: "tenant-a" },
|
||||
{ id: "tenant_b", name: "Tenant B", slug: "tenant-b" },
|
||||
];
|
||||
const existing = { id: "key_a", tenantId: "tenant_a", alias: "Primary", expires: null, active: true };
|
||||
|
||||
function requestFor(path: string, values: Record<string, string>) {
|
||||
return new Request(`https://admin.example.test${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(values),
|
||||
});
|
||||
}
|
||||
|
||||
function callCreate(values: Record<string, string>) {
|
||||
return runWithRlsContext({ userId: operator.id }, () =>
|
||||
createAction({
|
||||
request: requestFor("/api/keys/new", values),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/api/keys/new",
|
||||
} as ActionFunctionArgs)
|
||||
) as Promise<Response>;
|
||||
}
|
||||
|
||||
function callEdit(values: Record<string, string>) {
|
||||
return runWithRlsContext({ userId: operator.id }, () =>
|
||||
editAction({
|
||||
request: requestFor("/api/keys/key_a", values),
|
||||
params: { id: "key_a" },
|
||||
context: {},
|
||||
unstable_pattern: "admin/api/keys/$id",
|
||||
} as ActionFunctionArgs)
|
||||
) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin API key route RLS contexts", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: operator.id } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUser).mockResolvedValue(operator as never);
|
||||
vi.mocked(adminGetAllTenantsIdsAndNames).mockResolvedValue(tenants);
|
||||
vi.mocked(adminGetApiKeyById).mockResolvedValue(existing as never);
|
||||
vi.mocked(getApiKeyByAlias).mockResolvedValue(null as never);
|
||||
vi.mocked(getApiKeys).mockResolvedValue([existing] as never);
|
||||
vi.mocked(createApiKey).mockResolvedValue({ ...existing, id: "key_b", tenantId: "tenant_b" } as never);
|
||||
vi.mocked(updateApiKey).mockResolvedValue(existing as never);
|
||||
vi.mocked(deleteApiKey).mockResolvedValue(existing as never);
|
||||
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
|
||||
vi.mocked(createAdminLog).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
it("creates a key and its event only inside the selected tenant context", async () => {
|
||||
vi.mocked(getApiKeyByAlias).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
return null;
|
||||
});
|
||||
vi.mocked(createApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
return { ...existing, id: "key_b", tenantId: "tenant_b" } as never;
|
||||
});
|
||||
vi.mocked(EventsService.create).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
});
|
||||
|
||||
const response = await callCreate({ action: "create", "tenant-id": "tenant_b", alias: "Primary", active: "on" });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.created")}`);
|
||||
expect(createApiKey).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_b", createdByUserId: operator.id }));
|
||||
});
|
||||
|
||||
it("rejects a forged tenant before probing aliases or creating a key", async () => {
|
||||
const response = await callCreate({ action: "create", "tenant-id": "tenant_forged", alias: "Primary" });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(getApiKeyByAlias).not.toHaveBeenCalled();
|
||||
expect(createApiKey).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects moving an existing key to another tenant", async () => {
|
||||
const response = await callEdit({ action: "edit", "tenant-id": "tenant_b", alias: "Moved", active: "on" });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "translated:models.apiKey.errors.tenantChangeNotAllowed" });
|
||||
expect(getApiKeys).not.toHaveBeenCalled();
|
||||
expect(updateApiKey).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates and deletes only inside the key's owning tenant context", async () => {
|
||||
vi.mocked(updateApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_a" });
|
||||
return existing as never;
|
||||
});
|
||||
vi.mocked(deleteApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_a" });
|
||||
return existing as never;
|
||||
});
|
||||
|
||||
const editResponse = await callEdit({ action: "edit", "tenant-id": "tenant_a", alias: "Updated", active: "on" });
|
||||
const deleteResponse = await callEdit({ action: "delete" });
|
||||
|
||||
expect(editResponse.status).toBe(302);
|
||||
expect(deleteResponse.status).toBe(302);
|
||||
expect(editResponse.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.saved")}`);
|
||||
expect(deleteResponse.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.deleted")}`);
|
||||
expect(updateApiKey).toHaveBeenCalledWith("key_a", expect.objectContaining({ tenantId: "tenant_a", alias: "Updated" }));
|
||||
expect(deleteApiKey).toHaveBeenCalledWith("key_a", "tenant_a");
|
||||
});
|
||||
});
|
||||
+35
-28
@@ -1,4 +1,5 @@
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useNavigate } from "react-router";
|
||||
import ApiKeyCreatedModal from "~/components/core/apiKeys/ApiKeyCreatedModal";
|
||||
@@ -7,7 +8,7 @@ import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
@@ -16,11 +17,11 @@ import { ApiKeyCreatedDto } from "~/modules/events/dtos/ApiKeyCreatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
tenants: Pick<Tenant, "id" | "name">[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const tenants = await adminGetAllTenants();
|
||||
const tenants = await adminGetAllTenantsIdsAndNames();
|
||||
const data: LoaderData = {
|
||||
tenants,
|
||||
};
|
||||
@@ -35,7 +36,7 @@ type ActionData = {
|
||||
};
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
export const action: ActionFunction = async ({ request, params: _params }) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
@@ -52,34 +53,40 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
const tenantExists = (await adminGetAllTenantsIdsAndNames()).some((tenant) => tenant.id === tenantId);
|
||||
if (!tenantExists) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
await runWithRlsContext({ tenantId }, async () => {
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
throw badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
});
|
||||
});
|
||||
// return success({ apiKey });
|
||||
return redirect(adminPath("api/keys", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.created")}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
|
||||
import { ApiKeyLogDto } from "~/modules/api/dtos/ApiKeyLogDto";
|
||||
@@ -9,14 +8,16 @@ import ApiKeyLogsDetails from "~/modules/api/components/ApiKeyLogsDetails";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { apiTabs } from "./index";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
items: ApiKeyLogDto[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
type ActionData = { intent: "delete"; ok?: true; messageKey?: string; messageValues?: { count: number }; errorKey?: string };
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
@@ -32,39 +33,29 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("action") === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
|
||||
await ApiKeyLogService.adminDeleteMany(ids);
|
||||
return Response.json({ success: true });
|
||||
const result = await ApiKeyLogService.adminDeleteMany(ids);
|
||||
if (result.rejectedTenantlessIds.length > 0) {
|
||||
return Response.json({ intent: "delete", errorKey: "admin.apiAdmin.logs.tenantlessDeleteDenied" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
return Response.json({ intent: "delete", ok: true, messageKey: "admin.apiAdmin.logs.deleted", messageValues: { count: ids.length } } satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm"), success: false }, { status: 400 });
|
||||
return Response.json({ intent: "delete", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
useSaveToast(actionData);
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<EditPageLayout title={t("models.apiCall.plural")} tabs={apiTabs(t)} fullWidth>
|
||||
<ApiKeyLogsDetails data={data} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user