Begin cert alerting

This commit is contained in:
Tuan Dang
2024-08-07 07:08:47 -07:00
parent 5af53d3398
commit 1690a9429c
32 changed files with 972 additions and 7 deletions
@@ -8,6 +8,7 @@ export enum ProjectPermissionActions {
}
export enum ProjectPermissionSub {
Alerts = "alerts",
Role = "role",
Member = "member",
Groups = "groups",
@@ -41,6 +42,7 @@ export type ProjectPermissionSet =
ProjectPermissionActions,
ProjectPermissionSub.Secrets | (ForcedSubject<ProjectPermissionSub.Secrets> & SubjectFields)
]
| [ProjectPermissionActions, ProjectPermissionSub.Alerts]
| [ProjectPermissionActions, ProjectPermissionSub.Role]
| [ProjectPermissionActions, ProjectPermissionSub.Tags]
| [ProjectPermissionActions, ProjectPermissionSub.Member]
+2
View File
@@ -0,0 +1,2 @@
export { useCreateAlert, useDeleteAlert,useUpdateAlert } from "./mutations";
export { useGetAlertById } from "./queries";
@@ -0,0 +1,48 @@
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
@@ -0,0 +1,20 @@
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)
});
};
+29
View File
@@ -0,0 +1,29 @@
export type TAlert = {
id: string;
name: string;
projectId: string;
alertBeforeDays: number;
recipientEmails: string;
createdAt: string;
updatedAt: string;
};
export type TCreateAlertDTO = {
projectId: string;
name: string;
alertBeforeDays: number;
emails: string[];
};
export type TUpdateAlertDTO = {
alertId: string;
projectId: string;
name?: string;
alertBeforeDays?: number;
emails?: string[];
};
export type TDeleteAlertDTO = {
alertId: string;
projectId: string;
};
+1
View File
@@ -1,5 +1,6 @@
export * from "./accessApproval";
export * from "./admin";
export * from "./alerts";
export * from "./apiKeys";
export * from "./auditLogs";
export * from "./auditLogStreams";
+4 -3
View File
@@ -3,7 +3,8 @@ export {
useDeleteGroupFromWorkspace,
useLeaveProject,
useMigrateProjectToV3,
useUpdateGroupWorkspaceRole} from "./mutations";
useUpdateGroupWorkspaceRole
} from "./mutations";
export {
useAddIdentityToWorkspace,
useCreateWorkspace,
@@ -22,6 +23,7 @@ export {
useGetWorkspaceIntegrations,
useGetWorkspaceSecrets,
useGetWorkspaceUsers,
useListWorkspaceAlerts,
useListWorkspaceCas,
useListWorkspaceCertificates,
useListWorkspaceGroups,
@@ -31,5 +33,4 @@ export {
useUpdateIdentityWorkspaceRole,
useUpdateUserWorkspaceRole,
useUpdateWsEnvironment,
useUpgradeProject
} from "./queries";
useUpgradeProject} from "./queries";
+17 -1
View File
@@ -2,6 +2,7 @@ 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";
@@ -62,7 +63,8 @@ export const workspaceKeys = {
slug: string;
offset: number;
limit: number;
}) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const
}) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const,
getWorkspaceAlerts: (workspaceId: string) => [{ workspaceId }, "workspace-alerts"] as const
};
const fetchWorkspaceById = async (workspaceId: string) => {
@@ -601,3 +603,17 @@ export const useListWorkspaceCertificates = ({
enabled: Boolean(projectSlug)
});
};
export const useListWorkspaceAlerts = ({ workspaceId }: { workspaceId: string }) => {
return useQuery({
queryKey: workspaceKeys.getWorkspaceAlerts(workspaceId),
queryFn: async () => {
const {
data: { alerts }
} = await apiRequest.get<{ alerts: TAlert[] }>(`/api/v2/workspace/${workspaceId}/alerts`);
return { alerts };
},
enabled: Boolean(workspaceId)
});
};
@@ -2,11 +2,12 @@ import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { withProjectPermission } from "@app/hoc";
import { CaTab, CertificatesTab } from "./components";
import { AlertsTab,CaTab, CertificatesTab } from "./components";
enum TabSections {
Ca = "certificate-authorities",
Certificates = "certificates"
Certificates = "certificates",
Alerts = "alerts"
}
export const CertificatesPage = withProjectPermission(
@@ -19,6 +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>
</TabList>
<TabPanel value={TabSections.Certificates}>
<CertificatesTab />
@@ -26,6 +28,9 @@ export const CertificatesPage = withProjectPermission(
<TabPanel value={TabSections.Ca}>
<CaTab />
</TabPanel>
<TabPanel value={TabSections.Alerts}>
<AlertsTab />
</TabPanel>
</Tabs>
</div>
</div>
@@ -0,0 +1,17 @@
import { motion } from "framer-motion";
import { AlertsSection } from "./components";
export const AlertsTab = () => {
return (
<motion.div
key="panel-alerts"
transition={{ duration: 0.15 }}
initial={{ opacity: 0, translateX: 30 }}
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: 30 }}
>
<AlertsSection />
</motion.div>
);
};
@@ -0,0 +1,133 @@
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 { useCreateAlert, useGetAlertById,useUpdateAlert } 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<["alert"]>;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["alert"]>, state?: boolean) => void;
};
export const AlertModal = ({ popUp, handlePopUpToggle }: Props) => {
const { currentWorkspace } = useWorkspace();
const projectId = currentWorkspace?.id || "";
const { data: alert } = useGetAlertById(
(popUp?.alert?.data as { alertId: string })?.alertId || ""
);
const { mutateAsync: createAlert } = useCreateAlert();
const { mutateAsync: updateAlert } = useUpdateAlert();
const {
control,
handleSubmit,
reset,
formState: { isSubmitting }
} = useForm<FormData>({
resolver: zodResolver(schema)
});
useEffect(() => {
if (alert) {
reset({
name: alert.name
});
} else {
reset({
name: ""
});
}
}, [alert]);
const onFormSubmit = async ({ name }: FormData) => {
try {
if (!projectId) return;
if (alert) {
// update
await updateAlert({
alertId: alert.id,
name,
projectId,
alertBeforeDays: 3,
emails: ["test"]
});
} else {
// create
await createAlert({
name,
projectId,
alertBeforeDays: 3,
emails: ["test"]
});
}
handlePopUpToggle("alert", false);
reset();
createNotification({
text: `Successfully ${alert ? "updated" : "created"} alert`,
type: "success"
});
} catch (err) {
console.error(err);
createNotification({
text: `Failed to ${alert ? "updated" : "created"} alert`,
type: "error"
});
}
};
return (
<Modal
isOpen={popUp?.alert?.isOpen}
onOpenChange={(isOpen) => {
handlePopUpToggle("alert", isOpen);
reset();
}}
>
<ModalContent title={`${alert ? "Edit" : "Create"} Alert`}>
<form onSubmit={handleSubmit(onFormSubmit)}>
<Controller
control={control}
defaultValue=""
name="name"
render={({ field, fieldState: { error } }) => (
<FormControl label="Name" isError={Boolean(error)} errorText={error?.message}>
<Input {...field} placeholder="My Alert" />
</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,81 @@
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 { useDeleteAlert } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
import { AlertModal } from "./AlertModal";
import { AlertsTable } from "./AlertsTable";
export const AlertsSection = () => {
const { currentWorkspace } = useWorkspace();
const projectId = currentWorkspace?.id || "";
const { mutateAsync: deleteAlert } = useDeleteAlert();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"alert",
"deleteAlert"
] as const);
const onRemoveAlertSubmit = async (alertId: string) => {
try {
if (!projectId) return;
await deleteAlert({
alertId,
projectId
});
await createNotification({
text: "Successfully deleted alert",
type: "success"
});
handlePopUpClose("deleteAlert");
} catch (err) {
console.error(err);
createNotification({
text: "Failed to delete alert",
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">Alerts</p>
<ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Alerts}>
{(isAllowed) => (
<Button
colorSchema="primary"
type="submit"
leftIcon={<FontAwesomeIcon icon={faPlus} />}
onClick={() => handlePopUpOpen("alert")}
isDisabled={!isAllowed}
>
Create Alert
</Button>
)}
</ProjectPermissionCan>
</div>
<AlertsTable handlePopUpOpen={handlePopUpOpen} />
<AlertModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<DeleteActionModal
isOpen={popUp.deleteAlert.isOpen}
title={`Are you sure want to remove the alert ${
(popUp?.deleteAlert?.data as { name: string })?.name || ""
} from the project?`}
onChange={(isOpen) => handlePopUpToggle("deleteAlert", isOpen)}
deleteKey="confirm"
onDeleteApproved={() =>
onRemoveAlertSubmit((popUp?.deleteAlert?.data as { alertId: string })?.alertId)
}
/>
</div>
);
};
@@ -0,0 +1,125 @@
import { faEllipsis, faExclamationCircle } 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 { useListWorkspaceAlerts } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
handlePopUpOpen: (popUpName: keyof UsePopUpState<["alert", "deleteAlert"]>, data?: {}) => void;
};
export const AlertsTable = ({ handlePopUpOpen }: Props) => {
const { currentWorkspace } = useWorkspace();
const projectId = currentWorkspace?.id || "";
const { data, isLoading } = useListWorkspaceAlerts({
workspaceId: projectId
});
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>
);
};
@@ -0,0 +1 @@
export { AlertsSection } from "./AlertsSection";
@@ -0,0 +1 @@
export { AlertsTab } from "./AlertsTab";
@@ -1,2 +1,3 @@
export { AlertsTab } from "./AlertsTab";
export { CaTab } from "./CaTab";
export { CertificatesTab } from "./CertificatesTab";