Added pki collection table, pki alert modal

This commit is contained in:
Tuan Dang
2024-08-07 17:09:07 -07:00
parent 1690a9429c
commit 556e4d62c4
44 changed files with 1442 additions and 244 deletions
@@ -8,7 +8,6 @@ export enum ProjectPermissionActions {
}
export enum ProjectPermissionSub {
Alerts = "alerts",
Role = "role",
Member = "member",
Groups = "groups",
@@ -29,6 +28,8 @@ export enum ProjectPermissionSub {
Identity = "identity",
CertificateAuthorities = "certificate-authorities",
Certificates = "certificates",
PkiAlerts = "pki-alerts",
PkiCollections = "pki-collections",
Kms = "kms"
}
@@ -42,7 +43,7 @@ export type ProjectPermissionSet =
ProjectPermissionActions,
ProjectPermissionSub.Secrets | (ForcedSubject<ProjectPermissionSub.Secrets> & SubjectFields)
]
| [ProjectPermissionActions, ProjectPermissionSub.Alerts]
| [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts]
| [ProjectPermissionActions, ProjectPermissionSub.Role]
| [ProjectPermissionActions, ProjectPermissionSub.Tags]
| [ProjectPermissionActions, ProjectPermissionSub.Member]
@@ -1,48 +0,0 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { workspaceKeys } from "../workspace/queries";
import { alertKeys } from "./queries";
import { TAlert, TCreateAlertDTO, TDeleteAlertDTO,TUpdateAlertDTO } from "./types";
export const useCreateAlert = () => {
const queryClient = useQueryClient();
return useMutation<TAlert, {}, TCreateAlertDTO>({
mutationFn: async (body) => {
const { data: alert } = await apiRequest.post<TAlert>("/api/v1/alerts", body);
return alert;
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceAlerts(projectId));
}
});
};
export const useUpdateAlert = () => {
const queryClient = useQueryClient();
return useMutation<TAlert, {}, TUpdateAlertDTO>({
mutationFn: async ({ alertId, ...body }) => {
const { data: alert } = await apiRequest.patch<TAlert>(`/api/v1/alerts/${alertId}`, body);
return alert;
},
onSuccess: (_, { projectId, alertId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceAlerts(projectId));
queryClient.invalidateQueries(alertKeys.getAlertById(alertId));
}
});
};
export const useDeleteAlert = () => {
const queryClient = useQueryClient();
return useMutation<TAlert, {}, TDeleteAlertDTO>({
mutationFn: async ({ alertId }) => {
const { data: alert } = await apiRequest.delete<TAlert>(`/api/v1/alerts/${alertId}`);
return alert;
},
onSuccess: (_, { projectId, alertId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceAlerts(projectId));
queryClient.invalidateQueries(alertKeys.getAlertById(alertId));
}
});
};
-20
View File
@@ -1,20 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TAlert } from "./types";
export const alertKeys = {
getAlertById: (alertId: string) => [{ alertId }, "alert"]
};
export const useGetAlertById = (alertId: string) => {
return useQuery({
queryKey: alertKeys.getAlertById(alertId),
queryFn: async () => {
const { data: alert } = await apiRequest.get<TAlert>(`/api/v1/alerts/${alertId}`);
return alert;
},
enabled: Boolean(alertId)
});
};
+2 -1
View File
@@ -1,6 +1,5 @@
export * from "./accessApproval";
export * from "./admin";
export * from "./alerts";
export * from "./apiKeys";
export * from "./auditLogs";
export * from "./auditLogStreams";
@@ -22,6 +21,8 @@ export * from "./ldapConfig";
export * from "./oidcConfig";
export * from "./orgAdmin";
export * from "./organization";
export * from "./pkiAlerts";
export * from "./pkiCollections";
export * from "./projectUserAdditionalPrivilege";
export * from "./rateLimit";
export * from "./roles";
@@ -0,0 +1,51 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { workspaceKeys } from "../workspace/queries";
import { pkiAlertKeys } from "./queries";
import { TCreatePkiAlertDTO, TDeletePkiAlertDTO, TPkiAlert, TUpdatePkiAlertDTO } from "./types";
export const useCreateAlert = () => {
const queryClient = useQueryClient();
return useMutation<TPkiAlert, {}, TCreatePkiAlertDTO>({
mutationFn: async (body) => {
const { data: alert } = await apiRequest.post<TPkiAlert>("/api/v1/pki/alerts", body);
return alert;
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId));
}
});
};
export const useUpdateAlert = () => {
const queryClient = useQueryClient();
return useMutation<TPkiAlert, {}, TUpdatePkiAlertDTO>({
mutationFn: async ({ alertId, ...body }) => {
const { data: alert } = await apiRequest.patch<TPkiAlert>(
`/api/v1/pki/alerts/${alertId}`,
body
);
return alert;
},
onSuccess: (_, { projectId, alertId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId));
queryClient.invalidateQueries(pkiAlertKeys.getPkiAlertById(alertId));
}
});
};
export const useDeleteAlert = () => {
const queryClient = useQueryClient();
return useMutation<TPkiAlert, {}, TDeletePkiAlertDTO>({
mutationFn: async ({ alertId }) => {
const { data: alert } = await apiRequest.delete<TPkiAlert>(`/api/v1/pki/alerts/${alertId}`);
return alert;
},
onSuccess: (_, { projectId, alertId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId));
queryClient.invalidateQueries(pkiAlertKeys.getPkiAlertById(alertId));
}
});
};
@@ -0,0 +1,20 @@
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TPkiAlert } from "./types";
export const pkiAlertKeys = {
getPkiAlertById: (alertId: string) => [{ alertId }, "alert"]
};
export const useGetAlertById = (alertId: string) => {
return useQuery({
queryKey: pkiAlertKeys.getPkiAlertById(alertId),
queryFn: async () => {
const { data: alert } = await apiRequest.get<TPkiAlert>(`/api/v1/pki/alerts/${alertId}`);
return alert;
},
enabled: Boolean(alertId)
});
};
@@ -1,29 +1,32 @@
export type TAlert = {
export type TPkiAlert = {
id: string;
name: string;
projectId: string;
pkiCollectionId: string;
alertBeforeDays: number;
recipientEmails: string;
createdAt: string;
updatedAt: string;
};
export type TCreateAlertDTO = {
export type TCreatePkiAlertDTO = {
projectId: string;
name: string;
pkiCollectionId: string;
alertBeforeDays: number;
emails: string[];
};
export type TUpdateAlertDTO = {
export type TUpdatePkiAlertDTO = {
alertId: string;
projectId: string;
pkiCollectionId?: string;
name?: string;
alertBeforeDays?: number;
emails?: string[];
};
export type TDeleteAlertDTO = {
export type TDeletePkiAlertDTO = {
alertId: string;
projectId: string;
};
@@ -0,0 +1,5 @@
export {
useCreatePkiCollection,
useDeletePkiCollection,
useUpdatePkiCollection} from "./mutations";
export { useGetPkiCollectionById } from "./queries";
@@ -0,0 +1,64 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { workspaceKeys } from "../workspace/queries";
// import { alertKeys } from "./queries";
// import { TAlert, TCreateAlertDTO, TDeleteAlertDTO, TUpdateAlertDTO } from "./types";
import { pkiCollectionKeys } from "./queries";
import {
TCreatePkiCollectionDTO,
TDeletePkiCollectionDTO,
TPkiCollection,
TUpdatePkiCollectionTO} from "./types";
export const useCreatePkiCollection = () => {
const queryClient = useQueryClient();
return useMutation<TPkiCollection, {}, TCreatePkiCollectionDTO>({
mutationFn: async (body) => {
const { data: pkiCollection } = await apiRequest.post<TPkiCollection>(
"/api/v1/pki/collections",
body
);
return pkiCollection;
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId));
}
});
};
export const useUpdatePkiCollection = () => {
const queryClient = useQueryClient();
return useMutation<TPkiCollection, {}, TUpdatePkiCollectionTO>({
mutationFn: async ({ collectionId, ...body }) => {
const { data: pkiCollection } = await apiRequest.patch<TPkiCollection>(
`/api/v1/pki/collections/${collectionId}`,
body
);
return pkiCollection;
},
onSuccess: (_, { projectId, collectionId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId));
queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionById(collectionId));
}
});
};
export const useDeletePkiCollection = () => {
const queryClient = useQueryClient();
return useMutation<TPkiCollection, {}, TDeletePkiCollectionDTO>({
mutationFn: async ({ collectionId }) => {
const { data: pkiCollection } = await apiRequest.delete<TPkiCollection>(
`/api/v1/pki/collections/${collectionId}`
);
return pkiCollection;
},
onSuccess: (_, { projectId, collectionId }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId));
queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionById(collectionId));
}
});
};
// TODO: add PKI Collection Item
@@ -0,0 +1,22 @@
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TPkiCollection } from "./types";
export const pkiCollectionKeys = {
getPkiCollectionById: (collectionId: string) => [{ collectionId }, "pki-collection"]
};
export const useGetPkiCollectionById = (collectionId: string) => {
return useQuery({
queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId),
queryFn: async () => {
const { data: pkiCollection } = await apiRequest.get<TPkiCollection>(
`/api/v1/pki/collections/${collectionId}`
);
return pkiCollection;
},
enabled: Boolean(collectionId)
});
};
@@ -0,0 +1,23 @@
export type TPkiCollection = {
id: string;
name: string;
projectId: string;
createdAt: string;
updatedAt: string;
};
export type TCreatePkiCollectionDTO = {
projectId: string;
name: string;
};
export type TUpdatePkiCollectionTO = {
collectionId: string;
projectId: string;
name?: string;
};
export type TDeletePkiCollectionDTO = {
collectionId: string;
projectId: string;
};
+3 -1
View File
@@ -27,10 +27,12 @@ export {
useListWorkspaceCas,
useListWorkspaceCertificates,
useListWorkspaceGroups,
useListWorkspacePkiCollections,
useNameWorkspaceSecrets,
useRenameWorkspace,
useToggleAutoCapitalization,
useUpdateIdentityWorkspaceRole,
useUpdateUserWorkspaceRole,
useUpdateWsEnvironment,
useUpgradeProject} from "./queries";
useUpgradeProject
} from "./queries";
+25 -4
View File
@@ -2,7 +2,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TAlert } from "../alerts/types";
import { CaStatus } from "../ca/enums";
import { TCertificateAuthority } from "../ca/types";
import { TCertificate } from "../certificates/types";
@@ -11,6 +10,8 @@ import { identitiesKeys } from "../identities/queries";
import { IdentityMembership } from "../identities/types";
import { IntegrationAuth } from "../integrationAuth/types";
import { TIntegration } from "../integrations/types";
import { TPkiAlert } from "../pkiAlerts/types";
import { TPkiCollection } from "../pkiCollections/types";
import { EncryptedSecret } from "../secrets/types";
import { userKeys } from "../users/queries";
import { TWorkspaceUser } from "../users/types";
@@ -64,7 +65,9 @@ export const workspaceKeys = {
offset: number;
limit: number;
}) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const,
getWorkspaceAlerts: (workspaceId: string) => [{ workspaceId }, "workspace-alerts"] as const
getWorkspacePkiAlerts: (workspaceId: string) => [{ workspaceId }, "workspace-alerts"] as const,
getWorkspacePkiCollections: (workspaceId: string) =>
[{ workspaceId }, "workspace-pki-collections"] as const
};
const fetchWorkspaceById = async (workspaceId: string) => {
@@ -606,14 +609,32 @@ export const useListWorkspaceCertificates = ({
export const useListWorkspaceAlerts = ({ workspaceId }: { workspaceId: string }) => {
return useQuery({
queryKey: workspaceKeys.getWorkspaceAlerts(workspaceId),
queryKey: workspaceKeys.getWorkspacePkiAlerts(workspaceId),
queryFn: async () => {
const {
data: { alerts }
} = await apiRequest.get<{ alerts: TAlert[] }>(`/api/v2/workspace/${workspaceId}/alerts`);
} = await apiRequest.get<{ alerts: TPkiAlert[] }>(
`/api/v2/workspace/${workspaceId}/pki-alerts`
);
return { alerts };
},
enabled: Boolean(workspaceId)
});
};
export const useListWorkspacePkiCollections = ({ workspaceId }: { workspaceId: string }) => {
return useQuery({
queryKey: workspaceKeys.getWorkspacePkiCollections(workspaceId),
queryFn: async () => {
const {
data: { collections }
} = await apiRequest.get<{ collections: TPkiCollection[] }>(
`/api/v2/workspace/${workspaceId}/pki-collections`
);
return { collections };
},
enabled: Boolean(workspaceId)
});
};
@@ -2,12 +2,12 @@ import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { withProjectPermission } from "@app/hoc";
import { AlertsTab,CaTab, CertificatesTab } from "./components";
import { AlertsTab, CaTab, CertificatesTab } from "./components";
enum TabSections {
Ca = "certificate-authorities",
Certificates = "certificates",
Alerts = "alerts"
Alerting = "alerting"
}
export const CertificatesPage = withProjectPermission(
@@ -20,7 +20,7 @@ export const CertificatesPage = withProjectPermission(
<TabList>
<Tab value={TabSections.Certificates}>Certificates</Tab>
<Tab value={TabSections.Ca}>Certificate Authorities</Tab>
<Tab value={TabSections.Alerts}>Alerting</Tab>
<Tab value={TabSections.Alerting}>Alerting</Tab>
</TabList>
<TabPanel value={TabSections.Certificates}>
<CertificatesTab />
@@ -28,7 +28,7 @@ export const CertificatesPage = withProjectPermission(
<TabPanel value={TabSections.Ca}>
<CaTab />
</TabPanel>
<TabPanel value={TabSections.Alerts}>
<TabPanel value={TabSections.Alerting}>
<AlertsTab />
</TabPanel>
</Tabs>
@@ -1,6 +1,6 @@
import { motion } from "framer-motion";
import { AlertsSection } from "./components";
import { AlertsSection,PkiCollectionSection } from "./components";
export const AlertsTab = () => {
return (
@@ -11,6 +11,7 @@ export const AlertsTab = () => {
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: 30 }}
>
<PkiCollectionSection />
<AlertsSection />
</motion.div>
);
@@ -4,15 +4,53 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
import {
Button,
FormControl,
Input,
Modal,
ModalContent,
Select,
SelectItem,
TextArea} from "@app/components/v2";
import { useWorkspace } from "@app/context";
import { useCreateAlert, useGetAlertById,useUpdateAlert } from "@app/hooks/api";
import {
useCreateAlert,
useGetAlertById,
useListWorkspacePkiCollections,
useUpdateAlert} from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
enum TimeUnit {
DAY = "days",
WEEK = "weeks",
MONTH = "months",
YEAR = "years"
}
const schema = z.object({
name: z.string().trim().min(1)
name: z.string().trim().min(1),
pkiCollectionId: z.string(),
alertBefore: z.string(),
alertUnit: z.nativeEnum(TimeUnit),
emails: z.string().trim()
});
const convertToDays = (unit: TimeUnit, value: number) => {
switch (unit) {
case TimeUnit.DAY:
return value;
case TimeUnit.WEEK:
return value * 7;
case TimeUnit.MONTH:
return value * 30;
case TimeUnit.YEAR:
return value * 365;
default:
throw new Error(`Unknown time unit: ${unit}`);
}
};
export type FormData = z.infer<typeof schema>;
type Props = {
@@ -28,6 +66,10 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
(popUp?.alert?.data as { alertId: string })?.alertId || ""
);
const { data: pkiCollections } = useListWorkspacePkiCollections({
workspaceId: projectId
});
const { mutateAsync: createAlert } = useCreateAlert();
const { mutateAsync: updateAlert } = useUpdateAlert();
@@ -37,13 +79,20 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
reset,
formState: { isSubmitting }
} = useForm<FormData>({
resolver: zodResolver(schema)
resolver: zodResolver(schema),
defaultValues: {
alertUnit: TimeUnit.DAY
}
});
useEffect(() => {
if (alert) {
reset({
name: alert.name
name: alert.name,
pkiCollectionId: alert.pkiCollectionId,
alertBefore: alert.alertBeforeDays.toString(),
alertUnit: TimeUnit.DAY,
emails: alert.recipientEmails
});
} else {
reset({
@@ -52,26 +101,41 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
}
}, [alert]);
const onFormSubmit = async ({ name }: FormData) => {
const onFormSubmit = async ({
name,
pkiCollectionId,
alertBefore,
alertUnit,
emails
}: FormData) => {
try {
if (!projectId) return;
const emailArray = emails
.split(",")
.map((email) => email.trim())
.filter((email) => email.length > 0);
const alertBeforeDays = convertToDays(alertUnit, Number(alertBefore));
if (alert) {
// update
await updateAlert({
alertId: alert.id,
pkiCollectionId,
name,
projectId,
alertBeforeDays: 3,
emails: ["test"]
alertBeforeDays,
emails: emailArray
});
} else {
// create
await createAlert({
name,
projectId,
alertBeforeDays: 3,
emails: ["test"]
pkiCollectionId,
alertBeforeDays,
emails: emailArray
});
}
@@ -107,11 +171,104 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
defaultValue=""
name="name"
render={({ field, fieldState: { error } }) => (
<FormControl label="Name" isError={Boolean(error)} errorText={error?.message}>
<FormControl
label="Name"
isError={Boolean(error)}
errorText={error?.message}
isRequired
>
<Input {...field} placeholder="My Alert" />
</FormControl>
)}
/>
<Controller
control={control}
name="pkiCollectionId"
defaultValue=""
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="PKI Collection"
errorText={error?.message}
isError={Boolean(error)}
isRequired
>
<Select
defaultValue={field.value}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full"
>
{(pkiCollections?.collections || []).map(({ id, name }) => (
<SelectItem value={id} key={`project-${id}`}>
{name}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
<div className="flex items-center">
<Controller
control={control}
defaultValue=""
name="alertBefore"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Alert Before"
isError={Boolean(error)}
errorText={error?.message}
className="w-full"
isRequired
>
<Input {...field} placeholder="5" type="number" min={1} />
</FormControl>
)}
/>
<Controller
control={control}
name="alertUnit"
defaultValue={TimeUnit.YEAR}
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
className="ml-4"
label="Alert Unit"
errorText={error?.message}
isError={Boolean(error)}
>
<Select
defaultValue={field.value}
{...field}
onValueChange={(e) => onChange(e)}
className="w-48"
>
<SelectItem value={TimeUnit.DAY}>Days</SelectItem>
<SelectItem value={TimeUnit.WEEK}>Weeks</SelectItem>
<SelectItem value={TimeUnit.MONTH}>Months</SelectItem>
<SelectItem value={TimeUnit.YEAR}>Years</SelectItem>
</Select>
</FormControl>
)}
/>
</div>
<Controller
control={control}
defaultValue=""
name="emails"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Recipient Email(s)"
isError={Boolean(error)}
errorText={error?.message}
isRequired
>
<TextArea
{...field}
placeholder="[email protected], [email protected], ..."
reSize="none"
/>
</FormControl>
)}
/>
<div className="flex items-center">
<Button
className="mr-4"
@@ -120,7 +277,7 @@ export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
isLoading={isSubmitting}
isDisabled={isSubmitting}
>
Create
{alert ? "Update" : "Create"}
</Button>
<Button colorSchema="secondary" variant="plain">
Cancel
@@ -0,0 +1,89 @@
import { faEllipsis } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Td,
Tr
} from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { useGetPkiCollectionById } from "@app/hooks/api";
import { TPkiAlert } from "@app/hooks/api/pkiAlerts/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
alert: TPkiAlert;
handlePopUpOpen: (popUpName: keyof UsePopUpState<["alert", "deleteAlert"]>, data?: {}) => void;
};
export const AlertRow = ({ alert, handlePopUpOpen }: Props) => {
const { data: pkiCollection } = useGetPkiCollectionById(alert.pkiCollectionId || "");
return (
<Tr className="h-10" key={`alert-${alert.id}`}>
<Td>{alert.name}</Td>
<Td>{alert.alertBeforeDays}</Td>
<Td>{pkiCollection ? pkiCollection.name : "-"}</Td>
<Td>
<DropdownMenu>
<DropdownMenuTrigger asChild className="rounded-lg">
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
<FontAwesomeIcon size="sm" icon={faEllipsis} />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="p-1">
<ProjectPermissionCan
I={ProjectPermissionActions.Edit}
a={ProjectPermissionSub.PkiAlerts}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
handlePopUpOpen("alert", {
alertId: alert.id
});
}}
disabled={!isAllowed}
>
Edit Alert
</DropdownMenuItem>
)}
</ProjectPermissionCan>
<ProjectPermissionCan
I={ProjectPermissionActions.Delete}
a={ProjectPermissionSub.PkiAlerts}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
isAllowed
? "hover:!bg-red-500 hover:!text-white"
: "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
handlePopUpOpen("deleteAlert", {
alertId: alert.id,
name: alert.name
});
}}
disabled={!isAllowed}
>
Delete Alert
</DropdownMenuItem>
)}
</ProjectPermissionCan>
</DropdownMenuContent>
</DropdownMenu>
</Td>
</Tr>
);
};
@@ -49,7 +49,10 @@ export const AlertsSection = () => {
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<div className="mb-4 flex justify-between">
<p className="text-xl font-semibold text-mineshaft-100">Alerts</p>
<ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Alerts}>
<ProjectPermissionCan
I={ProjectPermissionActions.Create}
a={ProjectPermissionSub.PkiAlerts}
>
{(isAllowed) => (
<Button
colorSchema="primary"
@@ -58,7 +61,7 @@ export const AlertsSection = () => {
onClick={() => handlePopUpOpen("alert")}
isDisabled={!isAllowed}
>
Create Alert
Create
</Button>
)}
</ProjectPermissionCan>
@@ -1,27 +1,21 @@
import { faEllipsis, faExclamationCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
import { faExclamationCircle } from "@fortawesome/free-solid-svg-icons";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
EmptyState,
Table,
TableContainer,
TableSkeleton,
TBody,
Td,
Th,
THead,
Tr
} from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub , useWorkspace } from "@app/context";
import { useWorkspace } from "@app/context";
import { useListWorkspaceAlerts } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { AlertRow } from "./AlertRow";
type Props = {
handlePopUpOpen: (popUpName: keyof UsePopUpState<["alert", "deleteAlert"]>, data?: {}) => void;
};
@@ -35,91 +29,33 @@ export const AlertsTable = ({ handlePopUpOpen }: Props) => {
});
return (
<div>
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Name</Th>
<Th>Status</Th>
<Th>Valid Until</Th>
<Th className="w-5" />
</Tr>
</THead>
<TBody>
{isLoading && <TableSkeleton columns={4} innerKey="project-alerts" />}
{!isLoading &&
data?.alerts.map((alert) => {
return (
<Tr className="h-10" key={`alert-${alert.id}`}>
<Td>{alert.name}</Td>
<Td>Test 2</Td>
<Td>Test 3</Td>
<Td>
<DropdownMenu>
<DropdownMenuTrigger asChild className="rounded-lg">
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
<FontAwesomeIcon size="sm" icon={faEllipsis} />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="p-1">
<ProjectPermissionCan
I={ProjectPermissionActions.Edit}
a={ProjectPermissionSub.Alerts}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
handlePopUpOpen("alert", {
alertId: alert.id
});
}}
disabled={!isAllowed}
>
Edit Alert
</DropdownMenuItem>
)}
</ProjectPermissionCan>
<ProjectPermissionCan
I={ProjectPermissionActions.Delete}
a={ProjectPermissionSub.Alerts}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
isAllowed
? "hover:!bg-red-500 hover:!text-white"
: "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
handlePopUpOpen("deleteAlert", {
alertId: alert.id,
name: alert.name
});
}}
disabled={!isAllowed}
>
Delete Alert
</DropdownMenuItem>
)}
</ProjectPermissionCan>
</DropdownMenuContent>
</DropdownMenu>
</Td>
</Tr>
);
})}
</TBody>
</Table>
{!isLoading && !data?.alerts?.length && (
<EmptyState title="No alerts have been created" icon={faExclamationCircle} />
)}
</TableContainer>
</div>
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Alert Name</Th>
<Th>Alert Before Days</Th>
<Th>Bound PKI Collection</Th>
<Th className="w-5" />
</Tr>
</THead>
<TBody>
{isLoading && <TableSkeleton columns={4} innerKey="project-alerts" />}
{!isLoading &&
data?.alerts.map((alert) => {
return (
<AlertRow
key={`alert-${alert.id}`}
alert={alert}
handlePopUpOpen={handlePopUpOpen}
/>
);
})}
</TBody>
</Table>
{!isLoading && !data?.alerts?.length && (
<EmptyState title="No alerts have been created" icon={faExclamationCircle} />
)}
</TableContainer>
);
};
@@ -0,0 +1,138 @@
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
import { useWorkspace } from "@app/context";
import {
useCreatePkiCollection,
useGetPkiCollectionById,
useUpdatePkiCollection
} from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
const schema = z.object({
name: z.string().trim().min(1)
});
export type FormData = z.infer<typeof schema>;
type Props = {
popUp: UsePopUpState<["pkiCollection"]>;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["pkiCollection"]>, state?: boolean) => void;
};
export const PkiCollectionModal = ({ popUp, handlePopUpToggle }: Props) => {
const { currentWorkspace } = useWorkspace();
const projectId = currentWorkspace?.id || "";
const { data: pkiCollection } = useGetPkiCollectionById(
(popUp?.pkiCollection?.data as { collectionId: string })?.collectionId || ""
);
const { mutateAsync: createPkiCollection } = useCreatePkiCollection();
const { mutateAsync: updatePkiCollection } = useUpdatePkiCollection();
const {
control,
handleSubmit,
reset,
formState: { isSubmitting }
} = useForm<FormData>({
resolver: zodResolver(schema)
});
useEffect(() => {
if (pkiCollection) {
reset({
name: pkiCollection.name
});
} else {
reset({
name: ""
});
}
}, [pkiCollection]);
const onFormSubmit = async ({ name }: FormData) => {
try {
if (!projectId) return;
if (pkiCollection) {
// update
await updatePkiCollection({
collectionId: pkiCollection.id,
name,
projectId
});
} else {
// create
await createPkiCollection({
name,
projectId
});
}
handlePopUpToggle("pkiCollection", false);
reset();
createNotification({
text: `Successfully ${pkiCollection ? "updated" : "created"} PKI collection`,
type: "success"
});
} catch (err) {
console.error(err);
createNotification({
text: `Failed to ${pkiCollection ? "updated" : "created"} PKI collection`,
type: "error"
});
}
};
return (
<Modal
isOpen={popUp?.pkiCollection?.isOpen}
onOpenChange={(isOpen) => {
handlePopUpToggle("pkiCollection", isOpen);
reset();
}}
>
<ModalContent title={`${pkiCollection ? "Edit" : "Create"} PKI Collection`}>
<form onSubmit={handleSubmit(onFormSubmit)}>
<Controller
control={control}
defaultValue=""
name="name"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Name"
isError={Boolean(error)}
errorText={error?.message}
isRequired
>
<Input {...field} placeholder="My Certificate Collection" />
</FormControl>
)}
/>
<div className="flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
isLoading={isSubmitting}
isDisabled={isSubmitting}
>
Create
</Button>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
</div>
</form>
</ModalContent>
</Modal>
);
};
@@ -0,0 +1,86 @@
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, DeleteActionModal } from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
import { useDeletePkiCollection } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
import { PkiCollectionModal } from "./PkiCollectionModal";
import { PkiCollectionTable } from "./PkiCollectionTable";
export const PkiCollectionSection = () => {
const { currentWorkspace } = useWorkspace();
const projectId = currentWorkspace?.id || "";
const { mutateAsync: deletePkiCollection } = useDeletePkiCollection();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"pkiCollection",
"deletePkiCollection"
] as const);
const onRemovePkiCollectionSubmit = async (collectionId: string) => {
try {
if (!projectId) return;
await deletePkiCollection({
collectionId,
projectId
});
await createNotification({
text: "Successfully deleted PKI collection",
type: "success"
});
handlePopUpClose("deletePkiCollection");
} catch (err) {
console.error(err);
createNotification({
text: "Failed to delete PKI collection",
type: "error"
});
}
};
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<div className="mb-4 flex justify-between">
<p className="text-xl font-semibold text-mineshaft-100">PKI Collection</p>
<ProjectPermissionCan
I={ProjectPermissionActions.Create}
a={ProjectPermissionSub.PkiCollections}
>
{(isAllowed) => (
<Button
colorSchema="primary"
type="submit"
leftIcon={<FontAwesomeIcon icon={faPlus} />}
onClick={() => handlePopUpOpen("pkiCollection")}
isDisabled={!isAllowed}
>
Create
</Button>
)}
</ProjectPermissionCan>
</div>
<PkiCollectionTable handlePopUpOpen={handlePopUpOpen} />
<PkiCollectionModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<DeleteActionModal
isOpen={popUp.deletePkiCollection.isOpen}
title={`Are you sure want to remove the alert ${
(popUp?.deletePkiCollection?.data as { name: string })?.name || ""
} from the project?`}
onChange={(isOpen) => handlePopUpToggle("deletePkiCollection", isOpen)}
deleteKey="confirm"
onDeleteApproved={() =>
onRemovePkiCollectionSubmit(
(popUp?.deletePkiCollection?.data as { collectionId: string })?.collectionId
)
}
/>
</div>
);
};
@@ -0,0 +1,124 @@
import { faBoxesStacked, faEllipsis } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
EmptyState,
Table,
TableContainer,
TableSkeleton,
TBody,
Td,
Th,
THead,
Tr
} from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
import { useListWorkspacePkiCollections } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
handlePopUpOpen: (
popUpName: keyof UsePopUpState<["pkiCollection", "deletePkiCollection"]>,
data?: {}
) => void;
};
export const PkiCollectionTable = ({ handlePopUpOpen }: Props) => {
const { currentWorkspace } = useWorkspace();
const projectId = currentWorkspace?.id || "";
const { data, isLoading } = useListWorkspacePkiCollections({
workspaceId: projectId
});
return (
<div>
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Name</Th>
<Th className="w-5" />
</Tr>
</THead>
<TBody>
{isLoading && <TableSkeleton columns={2} innerKey="pki-collections" />}
{!isLoading &&
data?.collections.map((pkiCollection) => {
return (
<Tr className="h-10" key={`pki-collection-${pkiCollection.id}`}>
<Td>{pkiCollection.name}</Td>
<Td>
<DropdownMenu>
<DropdownMenuTrigger asChild className="rounded-lg">
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
<FontAwesomeIcon size="sm" icon={faEllipsis} />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="p-1">
<ProjectPermissionCan
I={ProjectPermissionActions.Edit}
a={ProjectPermissionSub.PkiCollections}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
handlePopUpOpen("pkiCollection", {
collectionId: pkiCollection.id
});
}}
disabled={!isAllowed}
>
Edit PKI Collection
</DropdownMenuItem>
)}
</ProjectPermissionCan>
<ProjectPermissionCan
I={ProjectPermissionActions.Delete}
a={ProjectPermissionSub.PkiCollections}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
isAllowed
? "hover:!bg-red-500 hover:!text-white"
: "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
handlePopUpOpen("deletePkiCollection", {
collectionId: pkiCollection.id,
name: pkiCollection.name
});
}}
disabled={!isAllowed}
>
Delete PKI Collection
</DropdownMenuItem>
)}
</ProjectPermissionCan>
</DropdownMenuContent>
</DropdownMenu>
</Td>
</Tr>
);
})}
</TBody>
</Table>
{!isLoading && !data?.collections?.length && (
<EmptyState title="No collections have been created" icon={faBoxesStacked} />
)}
</TableContainer>
</div>
);
};
@@ -1 +1,2 @@
export { AlertsSection } from "./AlertsSection";
export { PkiCollectionSection } from "./PkiCollectionSection";