mirror of
https://github.com/docmost/docmost.git
synced 2025-11-20 00:51:11 +10:00
feat: api keys management (EE) (#1665)
* feat: api keys (EE) * improvements * fix table * fix route * remove token suffix * api settings * Fix * fix * fix * fix
This commit is contained in:
@ -35,6 +35,8 @@ import SpacesPage from "@/pages/spaces/spaces.tsx";
|
||||
import { MfaChallengePage } from "@/ee/mfa/pages/mfa-challenge-page";
|
||||
import { MfaSetupRequiredPage } from "@/ee/mfa/pages/mfa-setup-required-page";
|
||||
import SpaceTrash from "@/pages/space/space-trash.tsx";
|
||||
import UserApiKeys from "@/ee/api-key/pages/user-api-keys";
|
||||
import WorkspaceApiKeys from "@/ee/api-key/pages/workspace-api-keys";
|
||||
|
||||
export default function App() {
|
||||
const { t } = useTranslation();
|
||||
@ -96,8 +98,10 @@ export default function App() {
|
||||
path={"account/preferences"}
|
||||
element={<AccountPreferences />}
|
||||
/>
|
||||
<Route path={"account/api-keys"} element={<UserApiKeys />} />
|
||||
<Route path={"workspace"} element={<WorkspaceSettings />} />
|
||||
<Route path={"members"} element={<WorkspaceMembers />} />
|
||||
<Route path={"api-keys"} element={<WorkspaceApiKeys />} />
|
||||
<Route path={"groups"} element={<Groups />} />
|
||||
<Route path={"groups/:groupId"} element={<GroupInfo />} />
|
||||
<Route path={"spaces"} element={<Spaces />} />
|
||||
|
||||
@ -4,14 +4,15 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
interface NoTableResultsProps {
|
||||
colSpan: number;
|
||||
text?: string;
|
||||
}
|
||||
export default function NoTableResults({ colSpan }: NoTableResultsProps) {
|
||||
export default function NoTableResults({ colSpan, text }: NoTableResultsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={colSpan}>
|
||||
<Text fw={500} c="dimmed" ta="center">
|
||||
{t("No results found...")}
|
||||
{text || t("No results found...")}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
|
||||
@ -10,6 +10,7 @@ import { getWorkspaceMembers } from "@/features/workspace/services/workspace-ser
|
||||
import { getLicenseInfo } from "@/ee/licence/services/license-service.ts";
|
||||
import { getSsoProviders } from "@/ee/security/services/security-service.ts";
|
||||
import { getShares } from "@/features/share/services/share-service.ts";
|
||||
import { getApiKeys } from "@/ee/api-key";
|
||||
|
||||
export const prefetchWorkspaceMembers = () => {
|
||||
const params = { limit: 100, page: 1, query: "" } as QueryParams;
|
||||
@ -65,3 +66,17 @@ export const prefetchShares = () => {
|
||||
queryFn: () => getShares({ page: 1, limit: 100 }),
|
||||
});
|
||||
};
|
||||
|
||||
export const prefetchApiKeys = () => {
|
||||
queryClient.prefetchQuery({
|
||||
queryKey: ["api-key-list", { page: 1 }],
|
||||
queryFn: () => getApiKeys({ page: 1 }),
|
||||
});
|
||||
};
|
||||
|
||||
export const prefetchApiKeyManagement = () => {
|
||||
queryClient.prefetchQuery({
|
||||
queryKey: ["api-key-list", { page: 1 }],
|
||||
queryFn: () => getApiKeys({ page: 1, adminView: true }),
|
||||
});
|
||||
};
|
||||
|
||||
@ -21,6 +21,8 @@ import useUserRole from "@/hooks/use-user-role.tsx";
|
||||
import { useAtom } from "jotai/index";
|
||||
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||
import {
|
||||
prefetchApiKeyManagement,
|
||||
prefetchApiKeys,
|
||||
prefetchBilling,
|
||||
prefetchGroups,
|
||||
prefetchLicense,
|
||||
@ -60,6 +62,14 @@ const groupedData: DataGroup[] = [
|
||||
icon: IconBrush,
|
||||
path: "/settings/account/preferences",
|
||||
},
|
||||
{
|
||||
label: "API keys",
|
||||
icon: IconKey,
|
||||
path: "/settings/account/api-keys",
|
||||
isCloud: true,
|
||||
isEnterprise: true,
|
||||
showDisabledInNonEE: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@ -90,6 +100,15 @@ const groupedData: DataGroup[] = [
|
||||
{ label: "Groups", icon: IconUsersGroup, path: "/settings/groups" },
|
||||
{ label: "Spaces", icon: IconSpaces, path: "/settings/spaces" },
|
||||
{ label: "Public sharing", icon: IconWorld, path: "/settings/sharing" },
|
||||
{
|
||||
label: "API management",
|
||||
icon: IconKey,
|
||||
path: "/settings/api-keys",
|
||||
isCloud: true,
|
||||
isEnterprise: true,
|
||||
isAdmin: true,
|
||||
showDisabledInNonEE: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@ -195,6 +214,12 @@ export default function SettingsSidebar() {
|
||||
case "Public sharing":
|
||||
prefetchHandler = prefetchShares;
|
||||
break;
|
||||
case "API keys":
|
||||
prefetchHandler = prefetchApiKeys;
|
||||
break;
|
||||
case "API management":
|
||||
prefetchHandler = prefetchApiKeyManagement;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
@ -0,0 +1,72 @@
|
||||
import {
|
||||
Modal,
|
||||
Text,
|
||||
Stack,
|
||||
Alert,
|
||||
Group,
|
||||
Button,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
import CopyTextButton from "@/components/common/copy.tsx";
|
||||
|
||||
interface ApiKeyCreatedModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
apiKey: IApiKey;
|
||||
}
|
||||
|
||||
export function ApiKeyCreatedModal({
|
||||
opened,
|
||||
onClose,
|
||||
apiKey,
|
||||
}: ApiKeyCreatedModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (!apiKey) return null;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={t("API key created")}
|
||||
size="lg"
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Alert
|
||||
icon={<IconAlertTriangle size={16} />}
|
||||
title={t("Important")}
|
||||
color="red"
|
||||
>
|
||||
{t(
|
||||
"Make sure to copy your API key now. You won't be able to see it again!",
|
||||
)}
|
||||
</Alert>
|
||||
|
||||
<div>
|
||||
<Text size="sm" fw={500} mb="xs">
|
||||
{t("API key")}
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<TextInput
|
||||
variant="filled"
|
||||
style={{
|
||||
flex: 1,
|
||||
}}
|
||||
value={apiKey.token}
|
||||
readOnly
|
||||
/>
|
||||
|
||||
<CopyTextButton text={apiKey.token} />
|
||||
</Group>
|
||||
</div>
|
||||
|
||||
<Button fullWidth onClick={onClose} mt="md">
|
||||
{t("I've saved my API key")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
143
apps/client/src/ee/api-key/components/api-key-table.tsx
Normal file
143
apps/client/src/ee/api-key/components/api-key-table.tsx
Normal file
@ -0,0 +1,143 @@
|
||||
import { ActionIcon, Group, Menu, Table, Text } from "@mantine/core";
|
||||
import { IconDots, IconEdit, IconTrash } from "@tabler/icons-react";
|
||||
import { format } from "date-fns";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||
import React from "react";
|
||||
import NoTableResults from "@/components/common/no-table-results";
|
||||
|
||||
interface ApiKeyTableProps {
|
||||
apiKeys: IApiKey[];
|
||||
isLoading?: boolean;
|
||||
showUserColumn?: boolean;
|
||||
onUpdate?: (apiKey: IApiKey) => void;
|
||||
onRevoke?: (apiKey: IApiKey) => void;
|
||||
}
|
||||
|
||||
export function ApiKeyTable({
|
||||
apiKeys,
|
||||
isLoading,
|
||||
showUserColumn = false,
|
||||
onUpdate,
|
||||
onRevoke,
|
||||
}: ApiKeyTableProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const formatDate = (date: Date | string | null) => {
|
||||
if (!date) return t("Never");
|
||||
return format(new Date(date), "MMM dd, yyyy");
|
||||
};
|
||||
|
||||
const isExpired = (expiresAt: string | null) => {
|
||||
if (!expiresAt) return false;
|
||||
return new Date(expiresAt) < new Date();
|
||||
};
|
||||
|
||||
return (
|
||||
<Table.ScrollContainer minWidth={500}>
|
||||
<Table highlightOnHover verticalSpacing="sm">
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>{t("Name")}</Table.Th>
|
||||
{showUserColumn && <Table.Th>{t("User")}</Table.Th>}
|
||||
<Table.Th>{t("Last used")}</Table.Th>
|
||||
<Table.Th>{t("Expires")}</Table.Th>
|
||||
<Table.Th>{t("Created")}</Table.Th>
|
||||
<Table.Th></Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
|
||||
<Table.Tbody>
|
||||
{apiKeys && apiKeys.length > 0 ? (
|
||||
apiKeys.map((apiKey: IApiKey, index: number) => (
|
||||
<Table.Tr key={index}>
|
||||
<Table.Td>
|
||||
<Text fz="sm" fw={500}>
|
||||
{apiKey.name}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
|
||||
{showUserColumn && apiKey.creator && (
|
||||
<Table.Td>
|
||||
<Group gap="4" wrap="nowrap">
|
||||
<CustomAvatar
|
||||
avatarUrl={apiKey.creator?.avatarUrl}
|
||||
name={apiKey.creator.name}
|
||||
size="sm"
|
||||
/>
|
||||
<Text fz="sm" lineClamp={1}>
|
||||
{apiKey.creator.name}
|
||||
</Text>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
)}
|
||||
|
||||
<Table.Td>
|
||||
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{formatDate(apiKey.lastUsedAt)}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
|
||||
<Table.Td>
|
||||
{apiKey.expiresAt ? (
|
||||
isExpired(apiKey.expiresAt) ? (
|
||||
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{t("Expired")}
|
||||
</Text>
|
||||
) : (
|
||||
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{formatDate(apiKey.expiresAt)}
|
||||
</Text>
|
||||
)
|
||||
) : (
|
||||
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{t("Never")}
|
||||
</Text>
|
||||
)}
|
||||
</Table.Td>
|
||||
|
||||
<Table.Td>
|
||||
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{formatDate(apiKey.createdAt)}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
|
||||
<Table.Td>
|
||||
<Menu position="bottom-end" withinPortal>
|
||||
<Menu.Target>
|
||||
<ActionIcon variant="subtle" color="gray">
|
||||
<IconDots size={16} />
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown>
|
||||
{onUpdate && (
|
||||
<Menu.Item
|
||||
leftSection={<IconEdit size={16} />}
|
||||
onClick={() => onUpdate(apiKey)}
|
||||
>
|
||||
{t("Rename")}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{onRevoke && (
|
||||
<Menu.Item
|
||||
leftSection={<IconTrash size={16} />}
|
||||
color="red"
|
||||
onClick={() => onRevoke(apiKey)}
|
||||
>
|
||||
{t("Revoke")}
|
||||
</Menu.Item>
|
||||
)}
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
) : (
|
||||
<NoTableResults colSpan={showUserColumn ? 6 : 5} />
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
);
|
||||
}
|
||||
153
apps/client/src/ee/api-key/components/create-api-key-modal.tsx
Normal file
153
apps/client/src/ee/api-key/components/create-api-key-modal.tsx
Normal file
@ -0,0 +1,153 @@
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import { Modal, TextInput, Button, Group, Stack, Select } from "@mantine/core";
|
||||
import { useForm } from "@mantine/form";
|
||||
import { zodResolver } from "mantine-form-zod-resolver";
|
||||
import { z } from "zod";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useCreateApiKeyMutation } from "@/ee/api-key/queries/api-key-query";
|
||||
import { IconCalendar } from "@tabler/icons-react";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
|
||||
const DateInput = lazy(() =>
|
||||
import("@mantine/dates").then((module) => ({
|
||||
default: module.DateInput,
|
||||
})),
|
||||
);
|
||||
|
||||
interface CreateApiKeyModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: (response: IApiKey) => void;
|
||||
}
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
expiresAt: z.string().optional(),
|
||||
});
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export function CreateApiKeyModal({
|
||||
opened,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: CreateApiKeyModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [expirationOption, setExpirationOption] = useState<string>("30");
|
||||
const createApiKeyMutation = useCreateApiKeyMutation();
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
name: "",
|
||||
expiresAt: "",
|
||||
},
|
||||
});
|
||||
|
||||
const getExpirationDate = (): string | undefined => {
|
||||
if (expirationOption === "never") {
|
||||
return undefined;
|
||||
}
|
||||
if (expirationOption === "custom") {
|
||||
return form.values.expiresAt;
|
||||
}
|
||||
const days = parseInt(expirationOption);
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() + days);
|
||||
return date.toISOString();
|
||||
};
|
||||
|
||||
const getExpirationLabel = (days: number) => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() + days);
|
||||
const formatted = date.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
});
|
||||
return `${days} days (${formatted})`;
|
||||
};
|
||||
|
||||
const expirationOptions = [
|
||||
{ value: "30", label: getExpirationLabel(30) },
|
||||
{ value: "60", label: getExpirationLabel(60) },
|
||||
{ value: "90", label: getExpirationLabel(90) },
|
||||
{ value: "365", label: getExpirationLabel(365) },
|
||||
{ value: "custom", label: t("Custom") },
|
||||
{ value: "never", label: t("No expiration") },
|
||||
];
|
||||
|
||||
const handleSubmit = async (data: {
|
||||
name?: string;
|
||||
expiresAt?: string | Date;
|
||||
}) => {
|
||||
const groupData = {
|
||||
name: data.name,
|
||||
expiresAt: getExpirationDate(),
|
||||
};
|
||||
|
||||
try {
|
||||
const createdKey = await createApiKeyMutation.mutateAsync(groupData);
|
||||
onSuccess(createdKey);
|
||||
form.reset();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
//
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
form.reset();
|
||||
setExpirationOption("30");
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={handleClose}
|
||||
title={t("Create API Key")}
|
||||
size="md"
|
||||
>
|
||||
<form onSubmit={form.onSubmit((values) => handleSubmit(values))}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label={t("Name")}
|
||||
placeholder={t("Enter a descriptive name")}
|
||||
data-autofocus
|
||||
required
|
||||
{...form.getInputProps("name")}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label={t("Expiration")}
|
||||
data={expirationOptions}
|
||||
value={expirationOption}
|
||||
onChange={(value) => setExpirationOption(value || "30")}
|
||||
leftSection={<IconCalendar size={16} />}
|
||||
allowDeselect={false}
|
||||
/>
|
||||
|
||||
{expirationOption === "custom" && (
|
||||
<Suspense fallback={null}>
|
||||
<DateInput
|
||||
label={t("Custom expiration date")}
|
||||
placeholder={t("Select expiration date")}
|
||||
minDate={new Date()}
|
||||
{...form.getInputProps("expiresAt")}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={handleClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={createApiKeyMutation.isPending}>
|
||||
{t("Create")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
import { Modal, Text, Button, Group, Stack } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useRevokeApiKeyMutation } from "@/ee/api-key/queries/api-key-query.ts";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
|
||||
interface RevokeApiKeyModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
apiKey: IApiKey | null;
|
||||
}
|
||||
|
||||
export function RevokeApiKeyModal({
|
||||
opened,
|
||||
onClose,
|
||||
apiKey,
|
||||
}: RevokeApiKeyModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const revokeApiKeyMutation = useRevokeApiKeyMutation();
|
||||
|
||||
const handleRevoke = async () => {
|
||||
if (!apiKey) return;
|
||||
await revokeApiKeyMutation.mutateAsync({
|
||||
apiKeyId: apiKey.id,
|
||||
});
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={t("Revoke API key")}
|
||||
size="md"
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Text>
|
||||
{t("Are you sure you want to revoke this API key")}{" "}
|
||||
<strong>{apiKey?.name}</strong>?
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"This action cannot be undone. Any applications using this API key will stop working.",
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
color="red"
|
||||
onClick={handleRevoke}
|
||||
loading={revokeApiKeyMutation.isPending}
|
||||
>
|
||||
{t("Revoke")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
import { Modal, TextInput, Button, Group, Stack } from "@mantine/core";
|
||||
import { useForm } from "@mantine/form";
|
||||
import { zodResolver } from "mantine-form-zod-resolver";
|
||||
import { z } from "zod";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useUpdateApiKeyMutation } from "@/ee/api-key/queries/api-key-query";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
});
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
interface UpdateApiKeyModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
apiKey: IApiKey | null;
|
||||
}
|
||||
|
||||
export function UpdateApiKeyModal({
|
||||
opened,
|
||||
onClose,
|
||||
apiKey,
|
||||
}: UpdateApiKeyModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const updateApiKeyMutation = useUpdateApiKeyMutation();
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
validate: zodResolver(formSchema),
|
||||
initialValues: {
|
||||
name: "",
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (opened && apiKey) {
|
||||
form.setValues({ name: apiKey.name });
|
||||
}
|
||||
}, [opened, apiKey]);
|
||||
|
||||
const handleSubmit = async (data: { name?: string }) => {
|
||||
const apiKeyData = {
|
||||
apiKeyId: apiKey.id,
|
||||
name: data.name,
|
||||
};
|
||||
|
||||
await updateApiKeyMutation.mutateAsync(apiKeyData);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={t("Update API key")}
|
||||
size="md"
|
||||
>
|
||||
<form onSubmit={form.onSubmit((values) => handleSubmit(values))}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label={t("Token name")}
|
||||
placeholder={t("Enter a descriptive token name")}
|
||||
required
|
||||
{...form.getInputProps("name")}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={updateApiKeyMutation.isPending}>
|
||||
{t("Update")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
11
apps/client/src/ee/api-key/index.ts
Normal file
11
apps/client/src/ee/api-key/index.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export { ApiKeyTable } from "./components/api-key-table";
|
||||
export { CreateApiKeyModal } from "./components/create-api-key-modal";
|
||||
export { ApiKeyCreatedModal } from "./components/api-key-created-modal";
|
||||
export { UpdateApiKeyModal } from "./components/update-api-key-modal";
|
||||
export { RevokeApiKeyModal } from "./components/revoke-api-key-modal";
|
||||
|
||||
// Services
|
||||
export * from "./services/api-key-service";
|
||||
|
||||
// Types
|
||||
export * from "./types/api-key.types";
|
||||
106
apps/client/src/ee/api-key/pages/user-api-keys.tsx
Normal file
106
apps/client/src/ee/api-key/pages/user-api-keys.tsx
Normal file
@ -0,0 +1,106 @@
|
||||
import React, { useState } from "react";
|
||||
import { Button, Group, Space } from "@mantine/core";
|
||||
import { Helmet } from "react-helmet-async";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import SettingsTitle from "@/components/settings/settings-title";
|
||||
import { getAppName } from "@/lib/config";
|
||||
import { ApiKeyTable } from "@/ee/api-key/components/api-key-table";
|
||||
import { CreateApiKeyModal } from "@/ee/api-key/components/create-api-key-modal";
|
||||
import { ApiKeyCreatedModal } from "@/ee/api-key/components/api-key-created-modal";
|
||||
import { UpdateApiKeyModal } from "@/ee/api-key/components/update-api-key-modal";
|
||||
import { RevokeApiKeyModal } from "@/ee/api-key/components/revoke-api-key-modal";
|
||||
import Paginate from "@/components/common/paginate";
|
||||
import { usePaginateAndSearch } from "@/hooks/use-paginate-and-search";
|
||||
import { useGetApiKeysQuery } from "@/ee/api-key/queries/api-key-query.ts";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
|
||||
export default function UserApiKeys() {
|
||||
const { t } = useTranslation();
|
||||
const { page, setPage } = usePaginateAndSearch();
|
||||
const [createModalOpened, setCreateModalOpened] = useState(false);
|
||||
const [createdApiKey, setCreatedApiKey] = useState<IApiKey | null>(null);
|
||||
const [updateModalOpened, setUpdateModalOpened] = useState(false);
|
||||
const [revokeModalOpened, setRevokeModalOpened] = useState(false);
|
||||
const [selectedApiKey, setSelectedApiKey] = useState<IApiKey | null>(null);
|
||||
const { data, isLoading } = useGetApiKeysQuery({ page });
|
||||
|
||||
const handleCreateSuccess = (response: IApiKey) => {
|
||||
setCreatedApiKey(response);
|
||||
};
|
||||
|
||||
const handleUpdate = (apiKey: IApiKey) => {
|
||||
setSelectedApiKey(apiKey);
|
||||
setUpdateModalOpened(true);
|
||||
};
|
||||
|
||||
const handleRevoke = (apiKey: IApiKey) => {
|
||||
setSelectedApiKey(apiKey);
|
||||
setRevokeModalOpened(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>
|
||||
{t("API keys")} - {getAppName()}
|
||||
</title>
|
||||
</Helmet>
|
||||
|
||||
<SettingsTitle title={t("API keys")} />
|
||||
|
||||
<Group justify="flex-end" mb="md">
|
||||
<Button onClick={() => setCreateModalOpened(true)}>
|
||||
{t("Create API Key")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
<ApiKeyTable
|
||||
apiKeys={data?.items || []}
|
||||
isLoading={isLoading}
|
||||
onUpdate={handleUpdate}
|
||||
onRevoke={handleRevoke}
|
||||
/>
|
||||
|
||||
<Space h="md" />
|
||||
|
||||
{data?.items.length > 0 && (
|
||||
<Paginate
|
||||
currentPage={page}
|
||||
hasPrevPage={data?.meta.hasPrevPage}
|
||||
hasNextPage={data?.meta.hasNextPage}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
)}
|
||||
|
||||
<CreateApiKeyModal
|
||||
opened={createModalOpened}
|
||||
onClose={() => setCreateModalOpened(false)}
|
||||
onSuccess={handleCreateSuccess}
|
||||
/>
|
||||
|
||||
<ApiKeyCreatedModal
|
||||
opened={!!createdApiKey}
|
||||
onClose={() => setCreatedApiKey(null)}
|
||||
apiKey={createdApiKey}
|
||||
/>
|
||||
|
||||
<UpdateApiKeyModal
|
||||
opened={updateModalOpened}
|
||||
onClose={() => {
|
||||
setUpdateModalOpened(false);
|
||||
setSelectedApiKey(null);
|
||||
}}
|
||||
apiKey={selectedApiKey}
|
||||
/>
|
||||
|
||||
<RevokeApiKeyModal
|
||||
opened={revokeModalOpened}
|
||||
onClose={() => {
|
||||
setRevokeModalOpened(false);
|
||||
setSelectedApiKey(null);
|
||||
}}
|
||||
apiKey={selectedApiKey}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
117
apps/client/src/ee/api-key/pages/workspace-api-keys.tsx
Normal file
117
apps/client/src/ee/api-key/pages/workspace-api-keys.tsx
Normal file
@ -0,0 +1,117 @@
|
||||
import React, { useState } from "react";
|
||||
import { Button, Group, Space, Text } from "@mantine/core";
|
||||
import { Helmet } from "react-helmet-async";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import SettingsTitle from "@/components/settings/settings-title";
|
||||
import { getAppName } from "@/lib/config";
|
||||
import { ApiKeyTable } from "@/ee/api-key/components/api-key-table";
|
||||
import { CreateApiKeyModal } from "@/ee/api-key/components/create-api-key-modal";
|
||||
import { ApiKeyCreatedModal } from "@/ee/api-key/components/api-key-created-modal";
|
||||
import { UpdateApiKeyModal } from "@/ee/api-key/components/update-api-key-modal";
|
||||
import { RevokeApiKeyModal } from "@/ee/api-key/components/revoke-api-key-modal";
|
||||
import Paginate from "@/components/common/paginate";
|
||||
import { usePaginateAndSearch } from "@/hooks/use-paginate-and-search";
|
||||
import { useGetApiKeysQuery } from "@/ee/api-key/queries/api-key-query.ts";
|
||||
import { IApiKey } from "@/ee/api-key";
|
||||
import useUserRole from '@/hooks/use-user-role.tsx';
|
||||
|
||||
export default function WorkspaceApiKeys() {
|
||||
const { t } = useTranslation();
|
||||
const { page, setPage } = usePaginateAndSearch();
|
||||
const [createModalOpened, setCreateModalOpened] = useState(false);
|
||||
const [createdApiKey, setCreatedApiKey] = useState<IApiKey | null>(null);
|
||||
const [updateModalOpened, setUpdateModalOpened] = useState(false);
|
||||
const [revokeModalOpened, setRevokeModalOpened] = useState(false);
|
||||
const [selectedApiKey, setSelectedApiKey] = useState<IApiKey | null>(null);
|
||||
const { data, isLoading } = useGetApiKeysQuery({ page, adminView: true });
|
||||
const { isAdmin } = useUserRole();
|
||||
|
||||
if (!isAdmin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleCreateSuccess = (response: IApiKey) => {
|
||||
setCreatedApiKey(response);
|
||||
};
|
||||
|
||||
const handleUpdate = (apiKey: IApiKey) => {
|
||||
setSelectedApiKey(apiKey);
|
||||
setUpdateModalOpened(true);
|
||||
};
|
||||
|
||||
const handleRevoke = (apiKey: IApiKey) => {
|
||||
setSelectedApiKey(apiKey);
|
||||
setRevokeModalOpened(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>
|
||||
{t("API management")} - {getAppName()}
|
||||
</title>
|
||||
</Helmet>
|
||||
|
||||
<SettingsTitle title={t("API management")} />
|
||||
|
||||
<Text size="md" c="dimmed" mb="md">
|
||||
{t("Manage API keys for all users in the workspace")}
|
||||
</Text>
|
||||
|
||||
<Group justify="flex-end" mb="md">
|
||||
<Button onClick={() => setCreateModalOpened(true)}>
|
||||
{t("Create API Key")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
<ApiKeyTable
|
||||
apiKeys={data?.items}
|
||||
isLoading={isLoading}
|
||||
showUserColumn
|
||||
onUpdate={handleUpdate}
|
||||
onRevoke={handleRevoke}
|
||||
/>
|
||||
|
||||
<Space h="md" />
|
||||
|
||||
{data?.items.length > 0 && (
|
||||
<Paginate
|
||||
currentPage={page}
|
||||
hasPrevPage={data?.meta.hasPrevPage}
|
||||
hasNextPage={data?.meta.hasNextPage}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
)}
|
||||
|
||||
<CreateApiKeyModal
|
||||
opened={createModalOpened}
|
||||
onClose={() => setCreateModalOpened(false)}
|
||||
onSuccess={handleCreateSuccess}
|
||||
/>
|
||||
|
||||
<ApiKeyCreatedModal
|
||||
opened={!!createdApiKey}
|
||||
onClose={() => setCreatedApiKey(null)}
|
||||
apiKey={createdApiKey}
|
||||
/>
|
||||
|
||||
<UpdateApiKeyModal
|
||||
opened={updateModalOpened}
|
||||
onClose={() => {
|
||||
setUpdateModalOpened(false);
|
||||
setSelectedApiKey(null);
|
||||
}}
|
||||
apiKey={selectedApiKey}
|
||||
/>
|
||||
|
||||
<RevokeApiKeyModal
|
||||
opened={revokeModalOpened}
|
||||
onClose={() => {
|
||||
setRevokeModalOpened(false);
|
||||
setSelectedApiKey(null);
|
||||
}}
|
||||
apiKey={selectedApiKey}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
97
apps/client/src/ee/api-key/queries/api-key-query.ts
Normal file
97
apps/client/src/ee/api-key/queries/api-key-query.ts
Normal file
@ -0,0 +1,97 @@
|
||||
import { IPagination, QueryParams } from "@/lib/types.ts";
|
||||
import {
|
||||
keepPreviousData,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
import {
|
||||
createApiKey,
|
||||
getApiKeys,
|
||||
IApiKey,
|
||||
ICreateApiKeyRequest,
|
||||
IUpdateApiKeyRequest,
|
||||
revokeApiKey,
|
||||
updateApiKey,
|
||||
} from "@/ee/api-key";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export function useGetApiKeysQuery(
|
||||
params?: QueryParams,
|
||||
): UseQueryResult<IPagination<IApiKey>, Error> {
|
||||
return useQuery({
|
||||
queryKey: ["api-key-list", params],
|
||||
queryFn: () => getApiKeys(params),
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
export function useRevokeApiKeyMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation<
|
||||
void,
|
||||
Error,
|
||||
{
|
||||
apiKeyId: string;
|
||||
}
|
||||
>({
|
||||
mutationFn: (data) => revokeApiKey(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: t("Revoked successfully") });
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (item) =>
|
||||
["api-key-list"].includes(item.queryKey[0] as string),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateApiKeyMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation<IApiKey, Error, ICreateApiKeyRequest>({
|
||||
mutationFn: (data) => createApiKey(data),
|
||||
onSuccess: () => {
|
||||
notifications.show({ message: t("API key created successfully") });
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (item) =>
|
||||
["api-key-list"].includes(item.queryKey[0] as string),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateApiKeyMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation<IApiKey, Error, IUpdateApiKeyRequest>({
|
||||
mutationFn: (data) => updateApiKey(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: t("Updated successfully") });
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (item) =>
|
||||
["api-key-list"].includes(item.queryKey[0] as string),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
},
|
||||
});
|
||||
}
|
||||
32
apps/client/src/ee/api-key/services/api-key-service.ts
Normal file
32
apps/client/src/ee/api-key/services/api-key-service.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import api from "@/lib/api-client";
|
||||
import {
|
||||
ICreateApiKeyRequest,
|
||||
IApiKey,
|
||||
IUpdateApiKeyRequest,
|
||||
} from "@/ee/api-key/types/api-key.types";
|
||||
import { IPagination, QueryParams } from "@/lib/types.ts";
|
||||
|
||||
export async function getApiKeys(
|
||||
params?: QueryParams,
|
||||
): Promise<IPagination<IApiKey>> {
|
||||
const req = await api.post("/api-keys", { ...params });
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function createApiKey(
|
||||
data: ICreateApiKeyRequest,
|
||||
): Promise<IApiKey> {
|
||||
const req = await api.post<IApiKey>("/api-keys/create", data);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function updateApiKey(
|
||||
data: IUpdateApiKeyRequest,
|
||||
): Promise<IApiKey> {
|
||||
const req = await api.post<IApiKey>("/api-keys/update", data);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function revokeApiKey(data: { apiKeyId: string }): Promise<void> {
|
||||
await api.post("/api-keys/revoke", data);
|
||||
}
|
||||
23
apps/client/src/ee/api-key/types/api-key.types.ts
Normal file
23
apps/client/src/ee/api-key/types/api-key.types.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { IUser } from "@/features/user/types/user.types.ts";
|
||||
|
||||
export interface IApiKey {
|
||||
id: string;
|
||||
name: string;
|
||||
token?: string;
|
||||
creatorId: string;
|
||||
workspaceId: string;
|
||||
expiresAt: string | null;
|
||||
lastUsedAt: string | null;
|
||||
createdAt: string;
|
||||
creator: Partial<IUser>;
|
||||
}
|
||||
|
||||
export interface ICreateApiKeyRequest {
|
||||
name: string;
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
export interface IUpdateApiKeyRequest {
|
||||
apiKeyId: string;
|
||||
name: string;
|
||||
}
|
||||
@ -1,11 +1,12 @@
|
||||
import { Group, Box, Button, TextInput, Stack, Textarea } from "@mantine/core";
|
||||
import React, { useState } from "react";
|
||||
import { useCreateGroupMutation } from "@/features/group/queries/group-query.ts";
|
||||
import { useForm, zodResolver } from "@mantine/form";
|
||||
import { useForm } from "@mantine/form";
|
||||
import * as z from "zod";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { MultiUserSelect } from "@/features/group/components/multi-user-select.tsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { zodResolver } from 'mantine-form-zod-resolver';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().trim().min(2).max(50),
|
||||
|
||||
@ -4,10 +4,11 @@ import {
|
||||
useGroupQuery,
|
||||
useUpdateGroupMutation,
|
||||
} from "@/features/group/queries/group-query.ts";
|
||||
import { useForm, zodResolver } from "@mantine/form";
|
||||
import { useForm } from "@mantine/form";
|
||||
import * as z from "zod";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { zodResolver } from "mantine-form-zod-resolver";
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(2).max(50),
|
||||
|
||||
@ -22,6 +22,7 @@ import { IUser } from "@/features/user/types/user.types.ts";
|
||||
import { useEffect } from "react";
|
||||
import { validate as isValidUuid } from "uuid";
|
||||
import { queryClient } from "@/main.tsx";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export function useGetGroupsQuery(
|
||||
params?: QueryParams,
|
||||
@ -73,11 +74,12 @@ export function useCreateGroupMutation() {
|
||||
|
||||
export function useUpdateGroupMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation<IGroup, Error, Partial<IGroup>>({
|
||||
mutationFn: (data) => updateGroup(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Group updated successfully" });
|
||||
notifications.show({ message: t("Group updated successfully") });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["group", variables.groupId],
|
||||
});
|
||||
@ -91,11 +93,12 @@ export function useUpdateGroupMutation() {
|
||||
|
||||
export function useDeleteGroupMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (groupId: string) => deleteGroup({ groupId }),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Group deleted successfully" });
|
||||
notifications.show({ message: t("Group deleted successfully") });
|
||||
queryClient.refetchQueries({ queryKey: ["groups"] });
|
||||
},
|
||||
onError: (error) => {
|
||||
@ -119,11 +122,12 @@ export function useGroupMembersQuery(
|
||||
|
||||
export function useAddGroupMemberMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation<void, Error, { groupId: string; userIds: string[] }>({
|
||||
mutationFn: (data) => addGroupMember(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Added successfully" });
|
||||
notifications.show({ message: t("Added successfully") });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["groupMembers", variables.groupId],
|
||||
});
|
||||
@ -139,6 +143,7 @@ export function useAddGroupMemberMutation() {
|
||||
|
||||
export function useRemoveGroupMemberMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation<
|
||||
void,
|
||||
@ -150,7 +155,7 @@ export function useRemoveGroupMemberMutation() {
|
||||
>({
|
||||
mutationFn: (data) => removeGroupMember(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Removed successfully" });
|
||||
notifications.show({ message: t("Removed successfully") });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["groupMembers", variables.groupId],
|
||||
});
|
||||
|
||||
@ -2,6 +2,7 @@ export interface QueryParams {
|
||||
query?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
adminView?: boolean;
|
||||
}
|
||||
|
||||
export enum UserRole {
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import "@mantine/core/styles.css";
|
||||
import "@mantine/spotlight/styles.css";
|
||||
import "@mantine/notifications/styles.css";
|
||||
import '@mantine/dates/styles.css';
|
||||
|
||||
import ReactDOM from "react-dom/client";
|
||||
import App from "./App.tsx";
|
||||
import { mantineCssResolver, theme } from "@/theme";
|
||||
|
||||
Reference in New Issue
Block a user