Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

refactor

Matheus Nogueirad26178d5759a
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/ProductSettingsPage.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/ProductSettingsPage.tsx
index 8652292cd2..2e3a12c0b3 100644
--- a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/ProductSettingsPage.tsx
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/ProductSettingsPage.tsx
@@ -22,6 +22,7 @@ import { useUpdateOrg } from "@app/hooks/api/organization/queries";
import { ProjectType } from "@app/hooks/api/projects/types";
import { HoneyTokenSection } from "./honey-token-config/HoneyTokenSection";
+import { ProjectTemplatesSection } from "./project-templates/ProjectTemplatesSection";
export const ProductSettingsPage = () => {
const { currentOrg } = useOrganization();
@@ -55,6 +56,7 @@ export const ProductSettingsPage = () => {
description="Configure organization-wide settings for secrets management projects."
/>
<div className="flex flex-col gap-4 px-8 pb-8">
+ <ProjectTemplatesSection />
<HoneyTokenSection />
<Card>
<CardHeader>
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/DeleteProjectTemplateModal.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/DeleteProjectTemplateModal.tsx
new file mode 100644
index 0000000000..33b54afcab
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/DeleteProjectTemplateModal.tsx
@@ -0,0 +1,40 @@
+import { createNotification } from "@app/components/notifications";
+import { DeleteActionModal } from "@app/components/v2";
+import { TProjectTemplate, useDeleteProjectTemplate } from "@app/hooks/api/projectTemplates";
+
+type Props = {
+ template?: TProjectTemplate;
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const DeleteProjectTemplateModal = ({ isOpen, onOpenChange, template }: Props) => {
+ const deleteTemplate = useDeleteProjectTemplate();
+
+ if (!template) return null;
+
+ const { id: templateId, name } = template;
+
+ const handleDeleteProjectTemplate = async () => {
+ await deleteTemplate.mutateAsync({
+ templateId
+ });
+
+ createNotification({
+ text: "Successfully removed project template",
+ type: "success"
+ });
+
+ onOpenChange(false);
+ };
+
+ return (
+ <DeleteActionModal
+ isOpen={isOpen}
+ onChange={onOpenChange}
+ title={`Are you sure you want to delete ${name}?`}
+ deleteKey="confirm"
+ onDeleteApproved={handleDeleteProjectTemplate}
+ />
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/EditProjectTemplateSection.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/EditProjectTemplateSection.tsx
new file mode 100644
index 0000000000..130870e8be
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/EditProjectTemplateSection.tsx
@@ -0,0 +1,59 @@
+import { ChevronLeft } from "lucide-react";
+
+import { Button, Empty, EmptyHeader, EmptyTitle, PageLoader } from "@app/components/v3";
+import {
+ InfisicalProjectTemplate,
+ TProjectTemplate,
+ useGetProjectTemplateById
+} from "@app/hooks/api/projectTemplates";
+
+import { EditProjectTemplate } from "./components";
+
+type Props = {
+ template: TProjectTemplate;
+ onBack: () => void;
+};
+
+export const EditProjectTemplateSection = ({ template, onBack }: Props) => {
+ const isInfisicalTemplate = Object.values(InfisicalProjectTemplate).includes(
+ template.name as InfisicalProjectTemplate
+ );
+
+ const { data: projectTemplate, isPending } = useGetProjectTemplateById(template.id, {
+ initialData: template,
+ enabled: !isInfisicalTemplate
+ });
+ const finalTemplate = isInfisicalTemplate ? template : projectTemplate;
+
+ return (
+ <div>
+ <Button
+ variant="ghost"
+ type="button"
+ onClick={onBack}
+ className="mb-6 px-0 text-mineshaft-300 hover:bg-transparent hover:text-mineshaft-100"
+ >
+ <ChevronLeft className="size-4" />
+ Back to Templates
+ </Button>
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {isPending ? (
+ <div className="flex h-[60vh] w-full items-center justify-center p-24">
+ <PageLoader />
+ </div>
+ ) : finalTemplate ? (
+ <EditProjectTemplate
+ isInfisicalTemplate={isInfisicalTemplate}
+ projectTemplate={finalTemplate}
+ onBack={onBack}
+ />
+ ) : (
+ <Empty className="py-12">
+ <EmptyHeader>
+ <EmptyTitle>Error: Unable to find project template.</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/EditProjectTemplate.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/EditProjectTemplate.tsx
new file mode 100644
index 0000000000..dcd49162ad
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/EditProjectTemplate.tsx
@@ -0,0 +1,130 @@
+import { Pencil, Trash2 } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import { DeleteActionModal } from "@app/components/v2";
+import { Button } from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context";
+import { getProjectTitle } from "@app/helpers/project";
+import { usePopUp } from "@app/hooks";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { TProjectTemplate, useDeleteProjectTemplate } from "@app/hooks/api/projectTemplates";
+
+import { ProjectTemplateDetailsModal } from "../../ProjectTemplateDetailsModal";
+import { ProjectTemplateEnvironmentsForm } from "./ProjectTemplateEnvironmentsForm";
+import { ProjectTemplateGroupsSection } from "./ProjectTemplateGroupsSection";
+import { ProjectTemplateIdentitiesSection } from "./ProjectTemplateIdentitiesSection";
+import { ProjectTemplateRolesSection } from "./ProjectTemplateRolesSection";
+import { ProjectTemplateUsersSection } from "./ProjectTemplateUsersSection";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+ onBack: () => void;
+ isInfisicalTemplate: boolean;
+};
+
+export const EditProjectTemplate = ({ isInfisicalTemplate, projectTemplate, onBack }: Props) => {
+ const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([
+ "removeTemplate",
+ "editDetails"
+ ] as const);
+
+ const { id: templateId, name, description, type } = projectTemplate;
+
+ const deleteProjectTemplate = useDeleteProjectTemplate();
+
+ const handleRemoveTemplate = async () => {
+ await deleteProjectTemplate.mutateAsync({
+ templateId
+ });
+ createNotification({
+ text: "Successfully removed project template",
+ type: "success"
+ });
+ onBack();
+ handlePopUpClose("removeTemplate");
+ };
+
+ return (
+ <>
+ <div className="mb-9 flex items-start justify-between gap-4">
+ <div className="flex-col">
+ <h3 className="text-2xl font-semibold tracking-normal">{name}</h3>
+ <h2 className="mt-2 text-base text-mineshaft-300">
+ {getProjectTitle(type)}
+ <span className="px-2 text-mineshaft-500">•</span>
+ {description || "Project Template"}
+ </h2>
+ </div>
+ {!isInfisicalTemplate && (
+ <div className="flex shrink-0 gap-3 pt-1">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Button
+ isDisabled={!isAllowed}
+ size="lg"
+ variant="outline"
+ onClick={() => handlePopUpOpen("editDetails")}
+ >
+ <Pencil className="size-4" />
+ Edit Details
+ </Button>
+ )}
+ </OrgPermissionCan>
+ <OrgPermissionCan
+ I={OrgPermissionActions.Delete}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Button
+ isDisabled={!isAllowed}
+ onClick={() => {
+ handlePopUpOpen("removeTemplate");
+ }}
+ size="lg"
+ variant="danger"
+ className="text-red-200"
+ >
+ <Trash2 className="size-4" />
+ Delete Template
+ </Button>
+ )}
+ </OrgPermissionCan>
+ </div>
+ )}
+ </div>
+ {type === ProjectType.SecretManager && (
+ <ProjectTemplateEnvironmentsForm
+ isInfisicalTemplate={isInfisicalTemplate}
+ projectTemplate={projectTemplate}
+ />
+ )}
+ <ProjectTemplateRolesSection
+ isInfisicalTemplate={isInfisicalTemplate}
+ projectTemplate={projectTemplate}
+ />
+ {!isInfisicalTemplate && (
+ <>
+ <ProjectTemplateUsersSection projectTemplate={projectTemplate} />
+ <ProjectTemplateGroupsSection projectTemplate={projectTemplate} />
+ <ProjectTemplateIdentitiesSection projectTemplate={projectTemplate} />
+ </>
+ )}
+ <ProjectTemplateDetailsModal
+ isOpen={popUp.editDetails.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("editDetails", isOpen)}
+ projectTemplate={projectTemplate}
+ />
+ <DeleteActionModal
+ isOpen={popUp.removeTemplate.isOpen}
+ title={`Are you sure you want to delete ${projectTemplate.name}?`}
+ deleteKey="confirm"
+ onChange={(isOpen) => handlePopUpToggle("removeTemplate", isOpen)}
+ onDeleteApproved={handleRemoveTemplate}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx
new file mode 100644
index 0000000000..899e01f4e0
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateEditRoleForm.tsx
@@ -0,0 +1,216 @@
+import { useEffect, useMemo, useState } from "react";
+import { Controller, FormProvider, useForm, useWatch } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ChevronLeftIcon, SaveIcon } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { Accordion, Button, Field, FieldError, FieldLabel, Input } from "@app/components/v3";
+import { ProjectPermissionSub } from "@app/context";
+import { isCustomProjectRole } from "@app/helpers/roles";
+import { TProjectTemplate, useUpdateProjectTemplate } from "@app/hooks/api/projectTemplates";
+import { slugSchema } from "@app/lib/schemas";
+import { AddPoliciesButton } from "@app/pages/project/RoleDetailsBySlugPage/components/AddPoliciesButton";
+import {
+ GeneralPermissionPolicies,
+ TPermissionAction
+} from "@app/pages/project/RoleDetailsBySlugPage/components/GeneralPermissionPolicies";
+import { PermissionEmptyState } from "@app/pages/project/RoleDetailsBySlugPage/components/PermissionEmptyState";
+import {
+ formRolePermission2API,
+ isConditionalSubjects,
+ PROJECT_PERMISSION_OBJECT,
+ projectRoleFormSchema,
+ rolePermission2Form
+} from "@app/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils";
+import { renderConditionalComponents } from "@app/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+ role?: TProjectTemplate["roles"][number];
+ onGoBack: () => void;
+ isDisabled?: boolean;
+};
+
+const formSchema = z.object({
+ slug: slugSchema(),
+ name: z.string().trim().min(1),
+ permissions: projectRoleFormSchema.shape.permissions
+});
+
+type TFormSchema = z.infer<typeof formSchema>;
+
+export const ProjectTemplateEditRoleForm = ({
+ onGoBack,
+ projectTemplate,
+ role,
+ isDisabled
+}: Props) => {
+ const [openPolicies, setOpenPolicies] = useState<string[]>([]);
+
+ const formMethods = useForm<TFormSchema>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: "",
+ slug: "",
+ permissions: {}
+ }
+ });
+
+ const {
+ handleSubmit,
+ control,
+ formState: { isDirty, isSubmitting },
+ reset
+ } = formMethods;
+
+ useEffect(() => {
+ if (role) {
+ reset({ ...role, permissions: rolePermission2Form(role.permissions) });
+ }
+ }, [role, reset]);
+
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const permissions = useWatch({ control, name: "permissions" });
+
+ const hasPermissions = useMemo(
+ () => Object.entries(permissions || {}).some(([key, value]) => key && value?.length > 0),
+ [permissions]
+ );
+
+ const onSubmit = async (form: TFormSchema) => {
+ await updateProjectTemplate.mutateAsync({
+ templateId: projectTemplate.id,
+ roles: [
+ ...projectTemplate.roles.filter(
+ (r) => r.slug !== role?.slug && isCustomProjectRole(r.slug) // filter out default roles as well
+ ),
+ {
+ ...form,
+ permissions: formRolePermission2API(form.permissions)
+ }
+ ]
+ });
+ onGoBack();
+ createNotification({
+ text: "Template roles successfully updated",
+ type: "success"
+ });
+ };
+
+ const handleFormSubmit = handleSubmit(onSubmit, (formErrors) => {
+ if (formErrors.permissions) {
+ const subjectsWithErrors = Object.keys(formErrors.permissions) as ProjectPermissionSub[];
+ setOpenPolicies((prev) => {
+ const newOpenPolicies = new Set(prev);
+ subjectsWithErrors.forEach((permissionSubject) => newOpenPolicies.add(permissionSubject));
+ return Array.from(newOpenPolicies);
+ });
+ }
+ });
+
+ return (
+ <form
+ onSubmit={handleFormSubmit}
+ className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"
+ >
+ <FormProvider {...formMethods}>
+ <div className="flex items-center justify-between border-b border-mineshaft-400 pb-2">
+ <Button variant="ghost" disabled={isSubmitting} onClick={onGoBack}>
+ <ChevronLeftIcon />
+ {isDisabled ? "Back" : "Cancel"}
+ </Button>
+ {!isDisabled && (
+ <div className="flex items-center gap-2">
+ {isDirty && (
+ <Button
+ type="button"
+ className="mr-4 text-muted"
+ variant="ghost"
+ disabled={isSubmitting}
+ onClick={() => {
+ if (role) {
+ reset({ ...role, permissions: rolePermission2Form(role.permissions) });
+ } else {
+ onGoBack();
+ }
+ }}
+ >
+ Discard
+ </Button>
+ )}
+ <Button variant="project" type="submit" disabled={isSubmitting || !isDirty}>
+ <SaveIcon />
+ Save
+ </Button>
+ <div className="ml-2 border-l border-border pl-4">
+ <AddPoliciesButton isDisabled={isDisabled} projectType={projectTemplate.type} />
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="mt-2 border-b border-gray-800 p-4 pt-2 first:rounded-t-md last:rounded-b-md">
+ {isDisabled ? (
+ <div className="flex flex-col">
+ <span className="text-lg font-medium">{role?.name}</span>
+ <span className="text-mineshaft-400">{role?.slug}</span>
+ </div>
+ ) : (
+ <div className="flex w-full gap-2">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-0 flex-1">
+ <FieldLabel>Name</FieldLabel>
+ <Input {...field} autoFocus placeholder="Role name..." />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="slug"
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-0 flex-1">
+ <FieldLabel>Slug</FieldLabel>
+ <Input {...field} placeholder="Role slug..." />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ </div>
+ )}
+ </div>
+ <div className="p-4">
+ <div className="mb-2 text-lg">Policies</div>
+ <PermissionEmptyState />
+ {hasPermissions && (
+ <Accordion
+ type="multiple"
+ value={openPolicies}
+ onValueChange={setOpenPolicies}
+ className="overflow-clip rounded-md border border-border bg-container"
+ >
+ {(Object.keys(PROJECT_PERMISSION_OBJECT) as ProjectPermissionSub[]).map((subject) => (
+ <GeneralPermissionPolicies
+ subject={subject}
+ actions={PROJECT_PERMISSION_OBJECT[subject].actions as TPermissionAction[]}
+ title={PROJECT_PERMISSION_OBJECT[subject].title}
+ description={PROJECT_PERMISSION_OBJECT[subject].description}
+ key={`project-permission-${subject}`}
+ isDisabled={isDisabled}
+ isOpen={openPolicies.includes(subject)}
+ isConditional={isConditionalSubjects(subject)}
+ >
+ {renderConditionalComponents(subject, isDisabled)}
+ </GeneralPermissionPolicies>
+ ))}
+ </Accordion>
+ )}
+ </div>
+ </FormProvider>
+ </form>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx
new file mode 100644
index 0000000000..213a70c7db
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateEnvironmentsForm.tsx
@@ -0,0 +1,277 @@
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ChevronDown, ChevronUp, Plus, Save, Trash2 } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ Field,
+ FieldError,
+ IconButton,
+ Input,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useSubscription } from "@app/context";
+import { TProjectTemplate, useUpdateProjectTemplate } from "@app/hooks/api/projectTemplates";
+import { slugSchema } from "@app/lib/schemas";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+ isInfisicalTemplate: boolean;
+};
+
+const formSchema = z.object({
+ environments: z
+ .object({
+ name: z.string().trim().min(1),
+ slug: slugSchema({ min: 1, max: 64 })
+ })
+ .array()
+ .nullish()
+});
+
+type TFormSchema = z.infer<typeof formSchema>;
+
+export const ProjectTemplateEnvironmentsForm = ({
+ projectTemplate,
+ isInfisicalTemplate
+}: Props) => {
+ const {
+ control,
+ handleSubmit,
+ formState: { isDirty, errors },
+ reset
+ } = useForm<TFormSchema>({
+ defaultValues: {
+ environments: projectTemplate.environments
+ },
+ resolver: zodResolver(formSchema)
+ });
+
+ const { subscription } = useSubscription();
+
+ const {
+ fields: environments,
+ move,
+ remove,
+ append
+ } = useFieldArray({ control, name: "environments" });
+
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const onFormSubmit = async (form: TFormSchema) => {
+ const { environments: updatedEnvs } = await updateProjectTemplate.mutateAsync({
+ environments: form.environments?.map((env, index) => ({
+ ...env,
+ position: index + 1
+ })),
+ templateId: projectTemplate.id
+ });
+
+ reset({ environments: updatedEnvs });
+
+ createNotification({
+ text: "Project template updated successfully",
+ type: "success"
+ });
+ };
+
+ const isEnvironmentLimitExceeded =
+ Boolean(subscription.environmentLimit) && environments.length >= subscription.environmentLimit;
+
+ return (
+ <form
+ onSubmit={handleSubmit(onFormSubmit)}
+ className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-7"
+ >
+ <div className="mb-8 flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-semibold tracking-normal">Project Environments</h2>
+ {!isInfisicalTemplate && (
+ <p className="mt-2 text-base text-mineshaft-300">
+ Add, rename, remove and reorder environments for this project template.
+ </p>
+ )}
+ </div>
+ {!isInfisicalTemplate && (
+ <div className="flex shrink-0 gap-2">
+ {isDirty && (
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Button type="submit" size="lg" variant="outline" isDisabled={!isAllowed}>
+ <Save className="size-4" />
+ Save Changes
+ </Button>
+ )}
+ </OrgPermissionCan>
+ )}
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ renderTooltip={isEnvironmentLimitExceeded ? true : undefined}
+ allowedLabel={`Plan environment limit of ${subscription.environmentLimit} exceeded. Contact Infisical to increase limit.`}
+ >
+ {(isAllowed) => (
+ <Button
+ onClick={() => append({ name: "", slug: "" })}
+ variant="project"
+ size="lg"
+ isDisabled={!isAllowed || isEnvironmentLimitExceeded}
+ >
+ <Plus className="size-4" />
+ Add Environment
+ </Button>
+ )}
+ </OrgPermissionCan>
+ </div>
+ )}
+ </div>
+ {errors.environments && (
+ <span className="my-4 text-sm text-red">{errors.environments.message}</span>
+ )}
+ <Table
+ className="table-fixed"
+ containerClassName="rounded-lg border-mineshaft-600 bg-mineshaft-800"
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Name</TableHead>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Slug</TableHead>
+ {!isInfisicalTemplate && <TableHead className="h-12 w-44 px-5" />}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {environments.map(({ id, name, slug }, pos) => (
+ <TableRow key={id} className="hover:bg-transparent">
+ <TableCell className="h-[56px] px-5 py-2 text-sm text-mineshaft-100">
+ {isInfisicalTemplate ? (
+ name
+ ) : (
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Controller
+ control={control}
+ name={`environments.${pos}.name`}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-0 grow">
+ <Input
+ disabled={!isAllowed}
+ {...field}
+ className="h-8 border-transparent px-2 text-sm shadow-none hover:border-mineshaft-500 focus-visible:border-ring"
+ placeholder="Name..."
+ />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ )}
+ </OrgPermissionCan>
+ )}
+ </TableCell>
+ <TableCell className="h-[56px] px-5 py-2 font-mono text-sm text-mineshaft-100">
+ {isInfisicalTemplate ? (
+ slug
+ ) : (
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Controller
+ control={control}
+ name={`environments.${pos}.slug`}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-0 grow">
+ <Input
+ disabled={!isAllowed}
+ {...field}
+ className="h-8 border-transparent px-2 font-mono text-sm shadow-none hover:border-mineshaft-500 focus-visible:border-ring"
+ placeholder="Slug..."
+ />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ )}
+ </OrgPermissionCan>
+ )}
+ </TableCell>
+ {!isInfisicalTemplate && (
+ <TableCell className="h-[56px] px-5 py-2 align-middle">
+ <div className="flex items-center justify-end gap-3 text-mineshaft-400">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ className={pos === 0 ? "pointer-events-none opacity-50" : ""}
+ onClick={() => move(pos, pos - 1)}
+ variant="ghost-muted"
+ size="xs"
+ aria-label="Move environment up"
+ isDisabled={pos === 0 || !isAllowed}
+ >
+ <ChevronUp className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ className={
+ pos === environments.length - 1 ? "pointer-events-none opacity-50" : ""
+ }
+ onClick={() => move(pos, pos + 1)}
+ variant="ghost-muted"
+ size="xs"
+ aria-label="Move environment down"
+ isDisabled={pos === environments.length - 1 || !isAllowed}
+ >
+ <ChevronDown className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ <div className="h-7 w-px bg-mineshaft-600" />
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={() => remove(pos)}
+ variant="ghost-muted"
+ size="xs"
+ aria-label="Remove environment"
+ isDisabled={!isAllowed}
+ >
+ <Trash2 className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ </div>
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </form>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateGroupsSection.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateGroupsSection.tsx
new file mode 100644
index 0000000000..648625c7bb
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateGroupsSection.tsx
@@ -0,0 +1,413 @@
+import { useMemo, useState } from "react";
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Plus, Save, Trash2 } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Empty,
+ EmptyHeader,
+ EmptyTitle,
+ Field,
+ FieldError,
+ FieldLabel,
+ FilterableSelect,
+ IconButton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
+import { useGetOrganizationGroups } from "@app/hooks/api";
+import {
+ TProjectTemplate,
+ TProjectTemplateGroup,
+ useUpdateProjectTemplate
+} from "@app/hooks/api/projectTemplates";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+};
+
+const formSchema = z.object({
+ groups: z
+ .object({
+ groupSlug: z.string().min(1),
+ roles: z.array(z.string()).min(1, "At least one role is required")
+ })
+ .array()
+});
+
+type TFormSchema = z.infer<typeof formSchema>;
+
+const addGroupFormSchema = z.object({
+ selectedGroups: z
+ .array(
+ z.object({
+ slug: z.string(),
+ name: z.string()
+ })
+ )
+ .min(1, "Select at least one group"),
+ roles: z
+ .array(
+ z.object({
+ slug: z.string(),
+ name: z.string()
+ })
+ )
+ .min(1, "Select at least one role")
+});
+
+type TAddGroupForm = z.infer<typeof addGroupFormSchema>;
+
+export const ProjectTemplateGroupsSection = ({ projectTemplate }: Props) => {
+ const { currentOrg } = useOrganization();
+ const orgId = currentOrg?.id || "";
+ const [isAddGroupModalOpen, setIsAddGroupModalOpen] = useState(false);
+
+ const { data: orgGroups } = useGetOrganizationGroups(orgId);
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isDirty, errors },
+ reset,
+ watch
+ } = useForm<TFormSchema>({
+ defaultValues: {
+ groups: (projectTemplate.groups || []) as TProjectTemplateGroup[]
+ },
+ resolver: zodResolver(formSchema)
+ });
+
+ const { fields: groups, remove, append } = useFieldArray({ control, name: "groups" });
+
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const onFormSubmit = async (form: TFormSchema) => {
+ await updateProjectTemplate.mutateAsync({
+ groups: form.groups.length > 0 ? form.groups : null,
+ templateId: projectTemplate.id
+ });
+
+ reset({ groups: form.groups });
+
+ createNotification({
+ text: "Project template groups updated successfully",
+ type: "success"
+ });
+ };
+
+ const handleDiscard = () => {
+ reset({ groups: (projectTemplate.groups || []) as TProjectTemplateGroup[] });
+ };
+
+ const availableRoles = useMemo(() => {
+ const predefinedRoles = [
+ { slug: "admin", name: "Admin" },
+ { slug: "member", name: "Member" },
+ { slug: "viewer", name: "Viewer" },
+ { slug: "no-access", name: "No Access" }
+ ];
+
+ const customRoles = projectTemplate.roles
+ .filter((role) => !["admin", "member", "viewer", "no-access", "custom"].includes(role.slug))
+ .map((role) => ({ slug: role.slug, name: role.name }));
+
+ return [...predefinedRoles, ...customRoles];
+ }, [projectTemplate.roles]);
+
+ const currentGroups = watch("groups");
+ const availableOrgGroups = useMemo(() => {
+ const addedGroupSlugs = new Set(currentGroups.map((g) => g.groupSlug.toLowerCase()));
+ return (orgGroups || [])
+ .filter((group) => !addedGroupSlugs.has(group.slug.toLowerCase()))
+ .map((group) => ({
+ slug: group.slug,
+ name: group.name
+ }));
+ }, [orgGroups, currentGroups]);
+
+ const getGroupName = (groupSlug: string) => {
+ const group = orgGroups?.find((g) => g.slug.toLowerCase() === groupSlug.toLowerCase());
+ return group?.name || groupSlug;
+ };
+
+ const {
+ control: addGroupControl,
+ handleSubmit: handleAddGroupSubmit,
+ reset: resetAddGroupForm,
+ watch: watchAddGroup,
+ formState: { errors: addGroupErrors }
+ } = useForm<TAddGroupForm>({
+ resolver: zodResolver(addGroupFormSchema),
+ defaultValues: {
+ selectedGroups: [],
+ roles: []
+ }
+ });
+
+ const selectedGroupsInModal = watchAddGroup("selectedGroups");
+ const selectedRolesInModal = watchAddGroup("roles");
+
+ const handleAddGroups = (form: TAddGroupForm) => {
+ form.selectedGroups.forEach((group) => {
+ append({
+ groupSlug: group.slug,
+ roles: form.roles.map((r) => r.slug)
+ });
+ });
+ resetAddGroupForm();
+ setIsAddGroupModalOpen(false);
+ };
+
+ const handleCloseAddGroupModal = () => {
+ resetAddGroupForm();
+ setIsAddGroupModalOpen(false);
+ };
+
+ return (
+ <>
+ <form
+ onSubmit={handleSubmit(onFormSubmit)}
+ className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-7"
+ >
+ <div className="mb-8 flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-semibold tracking-normal">Project Groups</h2>
+ <p className="mt-2 text-base text-mineshaft-300">
+ Add groups that will be automatically added to projects created from this template.
+ </p>
+ </div>
+
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <div className="flex gap-3">
+ {isAllowed && isDirty && (
+ <>
+ <Button onClick={handleDiscard} variant="ghost" type="button" size="lg">
+ Discard
+ </Button>
+ <Button type="submit" variant="outline" size="lg">
+ <Save className="size-4" />
+ Save Changes
+ </Button>
+ </>
+ )}
+ <Button
+ onClick={() => setIsAddGroupModalOpen(true)}
+ variant="project"
+ size="lg"
+ isDisabled={!isAllowed || availableOrgGroups.length === 0}
+ type="button"
+ >
+ <Plus className="size-4" />
+ Add Group
+ </Button>
+ </div>
+ )}
+ </OrgPermissionCan>
+ </div>
+ {errors.groups && <span className="my-4 text-sm text-red">{errors.groups.message}</span>}
+ <Table
+ className="table-fixed"
+ containerClassName="rounded-lg border-mineshaft-600 bg-mineshaft-800"
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Group</TableHead>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Roles</TableHead>
+ <TableHead className="h-12 w-20 px-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {groups.length > 0 ? (
+ groups.map(({ id }, pos) => (
+ <TableRow key={id} className="hover:bg-transparent">
+ <TableCell className="h-[58px] w-1/3 max-w-0 px-5 py-2">
+ <Controller
+ control={control}
+ name={`groups.${pos}.groupSlug`}
+ render={({ field }) => (
+ <p className="truncate">
+ <span className="text-sm font-medium text-mineshaft-100">
+ {getGroupName(field.value)}
+ </span>
+ </p>
+ )}
+ />
+ </TableCell>
+ <TableCell className="h-[58px] px-5 py-2">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Controller
+ control={control}
+ name={`groups.${pos}.roles`}
+ render={({ field, fieldState: { error } }) => {
+ const availableRoleSlugs = new Set(availableRoles.map((r) => r.slug));
+ const orphanedRoles = field.value
+ .filter((slug) => !availableRoleSlugs.has(slug))
+ .map((slug) => ({ slug, name: slug }));
+ const allOptions = [...availableRoles, ...orphanedRoles];
+
+ const selectedValues = allOptions.filter((role) =>
+ field.value.includes(role.slug)
+ );
+
+ return (
+ <Field className="mb-0 max-w-[786px]">
+ <FilterableSelect
+ isMulti
+ isDisabled={!isAllowed}
+ options={allOptions}
+ value={selectedValues}
+ onChange={(selected) => {
+ field.onChange(
+ (selected as { slug: string; name: string }[]).map(
+ (s) => s.slug
+ )
+ );
+ }}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ menuPosition="fixed"
+ />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ );
+ }}
+ />
+ )}
+ </OrgPermissionCan>
+ </TableCell>
+ <TableCell className="h-[58px] px-5 py-2">
+ <div className="flex justify-end">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={() => remove(pos)}
+ variant="ghost-muted"
+ size="xs"
+ aria-label="Remove group"
+ isDisabled={!isAllowed}
+ >
+ <Trash2 className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={3} className="h-24 p-0">
+ <Empty className="h-full rounded-none border-0 bg-mineshaft-800 p-6 md:p-8">
+ <EmptyHeader>
+ <EmptyTitle>No groups assigned to this template</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </form>
+
+ <Dialog open={isAddGroupModalOpen} onOpenChange={setIsAddGroupModalOpen}>
+ <DialogContent className="max-w-xl overflow-visible">
+ <DialogHeader>
+ <DialogTitle>Add Groups to Template</DialogTitle>
+ <DialogDescription>
+ Select groups and roles to add to this project template
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleAddGroupSubmit(handleAddGroups)}>
+ <div className="flex flex-col gap-4">
+ <Controller
+ control={addGroupControl}
+ name="selectedGroups"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Select groups</FieldLabel>
+ <FilterableSelect
+ isMulti
+ options={availableOrgGroups}
+ value={field.value}
+ onChange={field.onChange}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select one or more groups..."
+ noOptionsMessage={() =>
+ availableOrgGroups.length === 0
+ ? "All organization groups have been added"
+ : "No matching groups found"
+ }
+ />
+ {addGroupErrors.selectedGroups?.message && (
+ <FieldError>{addGroupErrors.selectedGroups.message}</FieldError>
+ )}
+ </Field>
+ )}
+ />
+ <Controller
+ control={addGroupControl}
+ name="roles"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Select roles</FieldLabel>
+ <FilterableSelect
+ isMulti
+ options={availableRoles}
+ value={field.value}
+ onChange={field.onChange}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ />
+ {addGroupErrors.roles?.message && (
+ <FieldError>{addGroupErrors.roles.message}</FieldError>
+ )}
+ </Field>
+ )}
+ />
+ </div>
+ <div className="mt-8 flex items-center gap-4">
+ <Button
+ type="submit"
+ isDisabled={selectedGroupsInModal.length === 0 || selectedRolesInModal.length === 0}
+ >
+ Add Groups
+ </Button>
+ <Button type="button" variant="ghost" onClick={handleCloseAddGroupModal}>
+ Cancel
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateIdentitiesSection.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateIdentitiesSection.tsx
new file mode 100644
index 0000000000..d3d404776b
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateIdentitiesSection.tsx
@@ -0,0 +1,656 @@
+import { useMemo, useState } from "react";
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { InfoIcon, Plus, Save, Trash2 } from "lucide-react";
+import { twMerge } from "tailwind-merge";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Badge,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Empty,
+ EmptyHeader,
+ EmptyTitle,
+ Field,
+ FieldError,
+ FieldLabel,
+ FilterableSelect,
+ IconButton,
+ Input,
+ OrgIcon,
+ ProjectIcon,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
+import { useDebounce } from "@app/hooks";
+import { useSearchOrgIdentityMemberships } from "@app/hooks/api";
+import {
+ TProjectTemplate,
+ TProjectTemplateIdentity,
+ TProjectTemplateProjectManagedIdentity,
+ useUpdateProjectTemplate
+} from "@app/hooks/api/projectTemplates";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+};
+
+const formSchema = z.object({
+ identities: z
+ .object({
+ identityId: z.string().uuid(),
+ identityName: z.string(),
+ roles: z.array(z.string()).min(1, "At least one role is required")
+ })
+ .array(),
+ projectManagedIdentities: z
+ .object({
+ name: z.string().trim().min(1),
+ roles: z.array(z.string()).min(1, "At least one role is required")
+ })
+ .array()
+});
+
+type TFormSchema = z.infer<typeof formSchema>;
+
+const addOrgIdentityFormSchema = z.object({
+ selectedIdentity: z.object({
+ id: z.string().uuid(),
+ name: z.string()
+ }),
+ roles: z
+ .array(
+ z.object({
+ slug: z.string(),
+ name: z.string()
+ })
+ )
+ .min(1, "Select at least one role")
+});
+
+type TAddOrgIdentityForm = z.infer<typeof addOrgIdentityFormSchema>;
+
+const addProjectIdentityFormSchema = z.object({
+ name: z.string().trim().min(1, "Name is required"),
+ roles: z
+ .array(
+ z.object({
+ slug: z.string(),
+ name: z.string()
+ })
+ )
+ .min(1, "Select at least one role")
+});
+
+type TAddProjectIdentityForm = z.infer<typeof addProjectIdentityFormSchema>;
+
+enum AddIdentityType {
+ CreateNew,
+ AssignExisting
+}
+
+export const ProjectTemplateIdentitiesSection = ({ projectTemplate }: Props) => {
+ const { currentOrg } = useOrganization();
+
+ const [isAddIdentityModalOpen, setIsAddIdentityModalOpen] = useState(false);
+
+ const [addMachineIdentityType, setAddMachineIdentityType] = useState<AddIdentityType>(
+ AddIdentityType.CreateNew
+ );
+
+ const [identitySearchInput, setIdentitySearchInput] = useState("");
+ const [debouncedIdentitySearch] = useDebounce(identitySearchInput, 300);
+
+ const { data: searchedIdentitiesResponse, isPending: isSearchingIdentities } =
+ useSearchOrgIdentityMemberships({
+ orgId: currentOrg.id,
+ limit: 100,
+ search: debouncedIdentitySearch ? { name: { $contains: debouncedIdentitySearch } } : {}
+ });
+ const searchedIdentities = searchedIdentitiesResponse
+ ? searchedIdentitiesResponse.identities.map((v) => v.identity)
+ : [];
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isDirty, errors },
+ reset,
+ watch
+ } = useForm<TFormSchema>({
+ defaultValues: {
+ identities: (projectTemplate.identities || []) as TProjectTemplateIdentity[],
+ projectManagedIdentities: (projectTemplate.projectManagedIdentities ||
+ []) as TProjectTemplateProjectManagedIdentity[]
+ },
+ resolver: zodResolver(formSchema)
+ });
+
+ const {
+ fields: identities,
+ remove: removeIdentity,
+ append: appendIdentity
+ } = useFieldArray({ control, name: "identities" });
+
+ const {
+ fields: projectManagedIdentities,
+ remove: removeProjectManagedIdentity,
+ append: appendProjectManagedIdentity
+ } = useFieldArray({ control, name: "projectManagedIdentities" });
+
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const onFormSubmit = async (form: TFormSchema) => {
+ await updateProjectTemplate.mutateAsync({
+ identities: form.identities.length > 0 ? form.identities : null,
+ projectManagedIdentities:
+ form.projectManagedIdentities.length > 0 ? form.projectManagedIdentities : null,
+ templateId: projectTemplate.id
+ });
+
+ reset({
+ identities: form.identities,
+ projectManagedIdentities: form.projectManagedIdentities
+ });
+
+ createNotification({
+ text: "Project template identities updated successfully",
+ type: "success"
+ });
+ };
+
+ const handleDiscard = () => {
+ reset({
+ identities: (projectTemplate.identities || []) as TProjectTemplateIdentity[],
+ projectManagedIdentities: (projectTemplate.projectManagedIdentities ||
+ []) as TProjectTemplateProjectManagedIdentity[]
+ });
+ };
+
+ const availableRoles = useMemo(() => {
+ const predefinedRoles = [
+ { slug: "admin", name: "Admin" },
+ { slug: "member", name: "Member" },
+ { slug: "viewer", name: "Viewer" },
+ { slug: "no-access", name: "No Access" }
+ ];
+
+ const customRoles = projectTemplate.roles
+ .filter((role) => !["admin", "member", "viewer", "no-access", "custom"].includes(role.slug))
+ .map((role) => ({ slug: role.slug, name: role.name }));
+
+ return [...predefinedRoles, ...customRoles];
+ }, [projectTemplate.roles]);
+
+ const currentIdentities = watch("identities");
+ const availableOrgIdentities = useMemo(() => {
+ const addedIdentityIds = new Set(currentIdentities.map((i) => i.identityId));
+ return searchedIdentities
+ .filter((identity) => !addedIdentityIds.has(identity.id))
+ .map((identity) => ({
+ id: identity.id,
+ name: identity.name
+ }));
+ }, [searchedIdentities, currentIdentities]);
+
+ const {
+ control: addOrgIdentityControl,
+ handleSubmit: handleAddOrgIdentitySubmit,
+ reset: resetAddOrgIdentityForm,
+ watch: watchAddOrgIdentity,
+ formState: { errors: addOrgIdentityErrors }
+ } = useForm<TAddOrgIdentityForm>({
+ resolver: zodResolver(addOrgIdentityFormSchema),
+ defaultValues: {
+ roles: []
+ }
+ });
+
+ const selectedOrgIdentity = watchAddOrgIdentity("selectedIdentity");
+ const selectedOrgRolesInModal = watchAddOrgIdentity("roles");
+
+ const handleAddOrgIdentity = (form: TAddOrgIdentityForm) => {
+ appendIdentity({
+ identityId: form.selectedIdentity.id,
+ identityName: form.selectedIdentity.name,
+ roles: form.roles.map((r) => r.slug)
+ });
+ resetAddOrgIdentityForm();
+ setIdentitySearchInput("");
+ setIsAddIdentityModalOpen(false);
+ };
+
+ const {
+ control: addProjectIdentityControl,
+ handleSubmit: handleAddProjectIdentitySubmit,
+ reset: resetAddProjectIdentityForm,
+ watch: watchAddProjectIdentity,
+ formState: { errors: addProjectIdentityErrors }
+ } = useForm<TAddProjectIdentityForm>({
+ resolver: zodResolver(addProjectIdentityFormSchema),
+ defaultValues: {
+ name: "",
+ roles: []
+ }
+ });
+
+ const projectIdentityName = watchAddProjectIdentity("name");
+ const selectedProjectRolesInModal = watchAddProjectIdentity("roles");
+
+ const handleAddProjectIdentity = (form: TAddProjectIdentityForm) => {
+ appendProjectManagedIdentity({
+ name: form.name,
+ roles: form.roles.map((r) => r.slug)
+ });
+ resetAddProjectIdentityForm();
+ setIsAddIdentityModalOpen(false);
+ };
+
+ const handleCloseAddIdentityModal = () => {
+ resetAddOrgIdentityForm();
+ resetAddProjectIdentityForm();
+ setIdentitySearchInput("");
+ setIsAddIdentityModalOpen(false);
+ };
+
+ const allIdentitiesForTable = useMemo(() => {
+ const orgManaged = identities.map((identity, index) => ({
+ type: "org" as const,
+ index,
+ id: identity.id,
+ identityId: identity.identityId,
+ name: identity.identityName,
+ roles: currentIdentities[index]?.roles || []
+ }));
+
+ const projectManaged = projectManagedIdentities.map((identity, index) => ({
+ type: "project" as const,
+ index,
+ id: identity.id,
+ name: identity.name,
+ roles: watch(`projectManagedIdentities.${index}.roles`) || []
+ }));
+
+ return [...projectManaged, ...orgManaged];
+ }, [identities, projectManagedIdentities, currentIdentities, watch]);
+
+ return (
+ <>
+ <form
+ onSubmit={handleSubmit(onFormSubmit)}
+ className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-7"
+ >
+ <div className="mb-8 flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-semibold tracking-normal">Project Machine Identities</h2>
+ <p className="mt-2 text-base text-mineshaft-300">
+ Add machine identities that will be automatically added to projects created from this
+ template.
+ </p>
+ </div>
+
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <div className="flex gap-3">
+ {isAllowed && isDirty && (
+ <>
+ <Button onClick={handleDiscard} variant="ghost" type="button" size="lg">
+ Discard
+ </Button>
+ <Button type="submit" variant="outline" size="lg">
+ <Save className="size-4" />
+ Save Changes
+ </Button>
+ </>
+ )}
+ <Button
+ onClick={() => setIsAddIdentityModalOpen(true)}
+ variant="project"
+ size="lg"
+ isDisabled={!isAllowed}
+ type="button"
+ >
+ <Plus className="size-4" />
+ Add Machine Identity
+ </Button>
+ </div>
+ )}
+ </OrgPermissionCan>
+ </div>
+ {errors.identities && (
+ <span className="my-4 text-sm text-red">{errors.identities.message}</span>
+ )}
+ {errors.projectManagedIdentities && (
+ <span className="my-4 text-sm text-red">{errors.projectManagedIdentities.message}</span>
+ )}
+ <Table
+ className="table-fixed"
+ containerClassName="rounded-lg border-mineshaft-600 bg-mineshaft-800"
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Identity</TableHead>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Roles</TableHead>
+ <TableHead className="h-12 w-20 px-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {allIdentitiesForTable.length > 0 ? (
+ allIdentitiesForTable.map((item) => (
+ <TableRow key={item.id} className="hover:bg-transparent">
+ <TableCell className="h-[58px] w-1/3 max-w-0 px-5 py-2">
+ <p className="flex items-center gap-3 truncate">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge isSquare variant={item.type === "project" ? "project" : "org"}>
+ {item.type === "project" ? <ProjectIcon /> : <OrgIcon />}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ {item.type === "project"
+ ? "Managed by project"
+ : "Managed by organization"}
+ </TooltipContent>
+ </Tooltip>
+ <span className="truncate text-sm font-medium text-mineshaft-100">
+ {item.name}
+ </span>
+ </p>
+ </TableCell>
+ <TableCell className="h-[58px] px-5 py-2">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Controller
+ control={control}
+ name={
+ item.type === "org"
+ ? `identities.${item.index}.roles`
+ : `projectManagedIdentities.${item.index}.roles`
+ }
+ render={({ field, fieldState: { error } }) => {
+ const availableRoleSlugs = new Set(availableRoles.map((r) => r.slug));
+ const orphanedRoles = field.value
+ .filter((slug) => !availableRoleSlugs.has(slug))
+ .map((slug) => ({ slug, name: slug }));
+ const allOptions = [...availableRoles, ...orphanedRoles];
+
+ const selectedValues = allOptions.filter((role) =>
+ field.value.includes(role.slug)
+ );
+
+ return (
+ <Field className="mb-0 max-w-[786px]">
+ <FilterableSelect
+ isMulti
+ isDisabled={!isAllowed}
+ options={allOptions}
+ value={selectedValues}
+ onChange={(selected) => {
+ field.onChange(
+ (selected as { slug: string; name: string }[]).map(
+ (s) => s.slug
+ )
+ );
+ }}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ menuPosition="fixed"
+ />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ );
+ }}
+ />
+ )}
+ </OrgPermissionCan>
+ </TableCell>
+ <TableCell className="h-[58px] px-5 py-2">
+ <div className="flex justify-end">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={() => {
+ if (item.type === "org") {
+ removeIdentity(item.index);
+ } else {
+ removeProjectManagedIdentity(item.index);
+ }
+ }}
+ variant="ghost-muted"
+ size="xs"
+ aria-label="Remove identity"
+ isDisabled={!isAllowed}
+ >
+ <Trash2 className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={3} className="h-24 p-0">
+ <Empty className="h-full rounded-none border-0 bg-mineshaft-800 p-6 md:p-8">
+ <EmptyHeader>
+ <EmptyTitle>No machine identities assigned to this template</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </form>
+
+ <Dialog open={isAddIdentityModalOpen} onOpenChange={setIsAddIdentityModalOpen}>
+ <DialogContent className="max-w-xl overflow-visible">
+ <DialogHeader>
+ <DialogTitle>Add Machine Identity to Template</DialogTitle>
+ <DialogDescription>
+ Create a new machine identity or assign an existing one
+ </DialogDescription>
+ </DialogHeader>
+ <div className="mb-4 flex items-center justify-center gap-x-2">
+ <div className="flex w-3/4 gap-x-0.5 rounded-md border border-mineshaft-600 bg-mineshaft-800 p-1">
+ <Button
+ variant="outline"
+ onClick={() => {
+ setAddMachineIdentityType(AddIdentityType.CreateNew);
+ }}
+ size="xs"
+ className={twMerge(
+ "min-w-[2.4rem] flex-1 rounded border-none hover:bg-mineshaft-600",
+ addMachineIdentityType === AddIdentityType.CreateNew
+ ? "bg-mineshaft-500"
+ : "bg-transparent"
+ )}
+ >
+ Create New
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => {
+ setAddMachineIdentityType(AddIdentityType.AssignExisting);
+ }}
+ size="xs"
+ className={twMerge(
+ "min-w-[2.4rem] flex-1 rounded border-none hover:bg-mineshaft-600",
+ addMachineIdentityType === AddIdentityType.AssignExisting
+ ? "bg-mineshaft-500"
+ : "bg-transparent"
+ )}
+ >
+ Assign Existing
+ </Button>
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon size={16} className="text-mineshaft-400" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm" side="right" align="start">
+ <p className="mb-2 text-mineshaft-300">
+ You can add machine identities to your template in one of two ways:
+ </p>
+ <ul className="ml-3.5 flex list-disc flex-col gap-y-4">
+ <li className="text-mineshaft-200">
+ <strong className="font-medium text-mineshaft-100">Create New</strong> - Define
+ a new machine identity that will be created when a project is made from this
+ template.
+ <p className="mt-2">
+ This method is recommended for autonomous teams that need to manage machine
+ identity authentication at the project level.
+ </p>
+ </li>
+ <li>
+ <strong className="font-medium text-mineshaft-100">Assign Existing</strong> -
+ Assign an existing machine identity from your organization.
+ <p className="mt-2">
+ This method is recommended for organizations that need to maintain centralized
+ control.
+ </p>
+ </li>
+ </ul>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ {addMachineIdentityType === AddIdentityType.CreateNew && (
+ <form onSubmit={handleAddProjectIdentitySubmit(handleAddProjectIdentity)}>
+ <Controller
+ control={addProjectIdentityControl}
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Name</FieldLabel>
+ <Input {...field} autoFocus placeholder="Machine Identity 1" />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ <Controller
+ control={addProjectIdentityControl}
+ name="roles"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Select roles</FieldLabel>
+ <FilterableSelect
+ isMulti
+ options={availableRoles}
+ value={field.value}
+ onChange={field.onChange}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ />
+ {addProjectIdentityErrors.roles?.message && (
+ <FieldError>{addProjectIdentityErrors.roles.message}</FieldError>
+ )}
+ </Field>
+ )}
+ />
+ <div className="mt-4 flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isDisabled={!projectIdentityName || selectedProjectRolesInModal.length === 0}
+ >
+ Add to Template
+ </Button>
+ <Button type="button" variant="ghost" onClick={handleCloseAddIdentityModal}>
+ Cancel
+ </Button>
+ </div>
+ </form>
+ )}
+ {addMachineIdentityType === AddIdentityType.AssignExisting && (
+ <form onSubmit={handleAddOrgIdentitySubmit(handleAddOrgIdentity)}>
+ <Controller
+ control={addOrgIdentityControl}
+ name="selectedIdentity"
+ render={({ field: { onChange, value }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Machine Identity</FieldLabel>
+ <FilterableSelect
+ value={value}
+ onChange={onChange}
+ isLoading={isSearchingIdentities}
+ placeholder="Select machine identity..."
+ autoFocus
+ options={availableOrgIdentities}
+ getOptionValue={(option) => option.id}
+ getOptionLabel={(option) => option.name}
+ onInputChange={(newValue) => setIdentitySearchInput(newValue)}
+ filterOption={() => true}
+ />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ )}
+ />
+ <Controller
+ control={addOrgIdentityControl}
+ name="roles"
+ render={({ field }) => (
+ <Field className="mt-4">
+ <FieldLabel>Select roles</FieldLabel>
+ <FilterableSelect
+ isMulti
+ options={availableRoles}
+ value={field.value}
+ onChange={field.onChange}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ />
+ {addOrgIdentityErrors.roles?.message && (
+ <FieldError>{addOrgIdentityErrors.roles.message}</FieldError>
+ )}
+ </Field>
+ )}
+ />
+ <div className="mt-4 flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isDisabled={!selectedOrgIdentity || selectedOrgRolesInModal.length === 0}
+ >
+ Assign to Template
+ </Button>
+ <Button type="button" variant="ghost" onClick={handleCloseAddIdentityModal}>
+ Cancel
+ </Button>
+ </div>
+ </form>
+ )}
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx
new file mode 100644
index 0000000000..ee9fad512e
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateRolesSection.tsx
@@ -0,0 +1,237 @@
+import { Plus, Rows3, Trash2, WrenchIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import { DeleteActionModal } from "@app/components/v2";
+import {
+ Button,
+ Empty,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useOrgPermission } from "@app/context";
+import { isCustomProjectRole } from "@app/helpers/roles";
+import { usePopUp } from "@app/hooks";
+import { TProjectTemplate, useUpdateProjectTemplate } from "@app/hooks/api/projectTemplates";
+import { TProjectRole } from "@app/hooks/api/roles/types";
+
+import { ProjectTemplateEditRoleForm } from "./ProjectTemplateEditRoleForm";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+ isInfisicalTemplate: boolean;
+};
+
+export const ProjectTemplateRolesSection = ({ projectTemplate, isInfisicalTemplate }: Props) => {
+ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
+ "removeRole",
+ "editRole"
+ ] as const);
+
+ const { permission } = useOrgPermission();
+
+ const { roles } = projectTemplate;
+
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const handleRemoveRole = async (slug: string) => {
+ const usersWithRole = projectTemplate.users?.filter((u) => u.roles.includes(slug)) || [];
+ const groupsWithRole = projectTemplate.groups?.filter((g) => g.roles.includes(slug)) || [];
+ const identitiesWithRole =
+ projectTemplate.identities?.filter((i) => i.roles.includes(slug)) || [];
+ const projectManagedIdentitiesWithRole =
+ projectTemplate.projectManagedIdentities?.filter((i) => i.roles.includes(slug)) || [];
+
+ const usageMessages: string[] = [];
+
+ if (usersWithRole.length > 0)
+ usageMessages.push(`${usersWithRole.length} user${usersWithRole.length === 1 ? "" : "s"}`);
+ if (groupsWithRole.length > 0)
+ usageMessages.push(`${groupsWithRole.length} group${groupsWithRole.length === 1 ? "" : "s"}`);
+ if (identitiesWithRole.length > 0 || projectManagedIdentitiesWithRole.length > 0) {
+ const totalIdentities = identitiesWithRole.length + projectManagedIdentitiesWithRole.length;
+ usageMessages.push(`${totalIdentities} identit${totalIdentities === 1 ? "y" : "ies"}`);
+ }
+
+ if (usageMessages.length > 0) {
+ createNotification({
+ text: `Cannot remove role "${slug}" because it is assigned to ${usageMessages.join(", ")}`,
+ type: "error"
+ });
+ handlePopUpClose("removeRole");
+ return;
+ }
+
+ await updateProjectTemplate.mutateAsync({
+ templateId: projectTemplate.id,
+ roles: projectTemplate.roles.filter(
+ (role) => role.slug !== slug && isCustomProjectRole(role.slug)
+ )
+ });
+
+ createNotification({
+ text: "Successfully removed role from template",
+ type: "success"
+ });
+ handlePopUpClose("removeRole");
+ };
+
+ const editRole = popUp?.editRole?.data as TProjectRole;
+ const roleToDelete = popUp?.removeRole?.data as TProjectRole;
+
+ return (
+ <div className="relative mb-6">
+ {popUp?.editRole.isOpen ? (
+ <ProjectTemplateEditRoleForm
+ onGoBack={() => handlePopUpClose("editRole")}
+ projectTemplate={projectTemplate}
+ role={editRole}
+ isDisabled={
+ permission.cannot(OrgPermissionActions.Edit, OrgPermissionSubjects.ProjectTemplates) ||
+ (editRole && !isCustomProjectRole(editRole.slug))
+ }
+ />
+ ) : (
+ <div className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-7">
+ <div className="mb-8 flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-semibold tracking-normal">Project Roles</h2>
+ <p className="mt-2 text-base text-mineshaft-300">
+ {isInfisicalTemplate
+ ? "Click a role to view the associated permissions."
+ : "Add, edit and remove roles for this project template."}
+ </p>
+ </div>
+ {!isInfisicalTemplate && (
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Button
+ onClick={() => {
+ handlePopUpOpen("editRole");
+ }}
+ variant="project"
+ size="lg"
+ isDisabled={!isAllowed}
+ >
+ <Plus className="size-4" />
+ Add Role
+ </Button>
+ )}
+ </OrgPermissionCan>
+ )}
+ </div>
+ <div>
+ <Table
+ className="table-fixed"
+ containerClassName="rounded-lg border-mineshaft-600 bg-mineshaft-800"
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Name</TableHead>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Type</TableHead>
+ <TableHead className="h-12 w-20 px-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {roles.length ? (
+ roles.map((role) => {
+ const isCustomRole = isCustomProjectRole(role.slug);
+
+ return (
+ <TableRow
+ key={role.slug}
+ className="group w-full cursor-pointer hover:bg-transparent"
+ role="button"
+ tabIndex={0}
+ onKeyDown={(evt) => {
+ if (evt.key === "Enter") {
+ handlePopUpOpen("editRole", role);
+ }
+ }}
+ onClick={() => handlePopUpOpen("editRole", role)}
+ >
+ <TableCell className="h-[56px] px-5 py-2 text-sm font-medium text-mineshaft-100">
+ {role.name}
+ </TableCell>
+ <TableCell className="h-[56px] px-5 py-2">
+ <span className="inline-flex items-center gap-1.5 rounded-md border border-mineshaft-500 bg-mineshaft-700 px-2 py-0.5 text-sm font-medium text-mineshaft-200">
+ {isCustomRole ? (
+ <>
+ <WrenchIcon className="size-4 text-mineshaft-300" />
+ Custom
+ </>
+ ) : (
+ <>
+ <Rows3 className="size-4 text-mineshaft-300" />
+ Platform
+ </>
+ )}
+ </span>
+ </TableCell>
+ <TableCell className="h-[56px] px-5 py-2">
+ <div className="flex justify-end">
+ {isCustomRole && (
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ renderTooltip
+ allowedLabel="Remove Role"
+ >
+ {(isAllowed) => (
+ <IconButton
+ variant="ghost-muted"
+ size="xs"
+ aria-label="delete-icon"
+ isDisabled={!isAllowed}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ handlePopUpOpen("removeRole", role);
+ }}
+ >
+ <Trash2 className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })
+ ) : (
+ <TableRow>
+ <TableCell colSpan={3} className="h-24 p-0">
+ <Empty className="h-full rounded-none border-0 bg-mineshaft-800 p-6 md:p-8">
+ <EmptyHeader>
+ <EmptyTitle>No roles assigned to template</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ <DeleteActionModal
+ isOpen={popUp.removeRole.isOpen}
+ deleteKey="remove"
+ title={`Are you sure you want to remove the role ${roleToDelete?.slug}?`}
+ onChange={(isOpen) => handlePopUpToggle("removeRole", isOpen)}
+ onDeleteApproved={() => handleRemoveRole(roleToDelete?.slug)}
+ />
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateUsersSection.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateUsersSection.tsx
new file mode 100644
index 0000000000..fda6a0301f
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/ProjectTemplateUsersSection.tsx
@@ -0,0 +1,412 @@
+import { useMemo, useState } from "react";
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Plus, Save, Trash2 } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Empty,
+ EmptyHeader,
+ EmptyTitle,
+ Field,
+ FieldError,
+ FieldLabel,
+ FilterableSelect,
+ IconButton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
+import {
+ TProjectTemplate,
+ TProjectTemplateUser,
+ useUpdateProjectTemplate
+} from "@app/hooks/api/projectTemplates";
+import { useGetOrgUsers } from "@app/hooks/api/users";
+
+type Props = {
+ projectTemplate: TProjectTemplate;
+};
+
+const formSchema = z.object({
+ users: z
+ .object({
+ username: z.string().min(1),
+ roles: z.array(z.string()).min(1, "At least one role is required")
+ })
+ .array()
+});
+
+type TFormSchema = z.infer<typeof formSchema>;
+
+const addUserFormSchema = z.object({
+ selectedUsers: z
+ .array(
+ z.object({
+ label: z.string(),
+ value: z.string()
+ })
+ )
+ .min(1, "Select at least one user"),
+ roles: z
+ .array(
+ z.object({
+ slug: z.string(),
+ name: z.string()
+ })
+ )
+ .min(1, "Select at least one role")
+});
+
+type TAddUserForm = z.infer<typeof addUserFormSchema>;
+
+export const ProjectTemplateUsersSection = ({ projectTemplate }: Props) => {
+ const { currentOrg } = useOrganization();
+ const orgId = currentOrg?.id || "";
+ const [isAddUserModalOpen, setIsAddUserModalOpen] = useState(false);
+
+ const { data: orgUsers } = useGetOrgUsers(orgId);
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isDirty, errors },
+ reset,
+ watch
+ } = useForm<TFormSchema>({
+ defaultValues: {
+ users: (projectTemplate.users || []) as TProjectTemplateUser[]
+ },
+ resolver: zodResolver(formSchema)
+ });
+
+ const { fields: users, remove, append } = useFieldArray({ control, name: "users" });
+
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const onFormSubmit = async (form: TFormSchema) => {
+ await updateProjectTemplate.mutateAsync({
+ users: form.users.length > 0 ? form.users : null,
+ templateId: projectTemplate.id
+ });
+
+ reset({ users: form.users });
+
+ createNotification({
+ text: "Project template users updated successfully",
+ type: "success"
+ });
+ };
+
+ const handleDiscard = () => {
+ reset({ users: (projectTemplate.users || []) as TProjectTemplateUser[] });
+ };
+
+ const availableRoles = useMemo(() => {
+ const predefinedRoles = [
+ { slug: "admin", name: "Admin" },
+ { slug: "member", name: "Member" },
+ { slug: "viewer", name: "Viewer" },
+ { slug: "no-access", name: "No Access" }
+ ];
+
+ const customRoles = projectTemplate.roles
+ .filter((role) => !["admin", "member", "viewer", "no-access", "custom"].includes(role.slug))
+ .map((role) => ({ slug: role.slug, name: role.name }));
+
+ return [...predefinedRoles, ...customRoles];
+ }, [projectTemplate.roles]);
+
+ const currentUsers = watch("users");
+ const availableOrgUsers = useMemo(() => {
+ const addedUsernames = new Set(currentUsers.map((u) => u.username.toLowerCase()));
+ return (orgUsers || [])
+ .filter((orgUser) => {
+ const username = orgUser.user.username?.toLowerCase();
+ return username && !addedUsernames.has(username);
+ })
+ .map((orgUser) => ({
+ value: orgUser.user.username,
+ label:
+ orgUser.user.firstName && orgUser.user.lastName
+ ? `${orgUser.user.firstName} ${orgUser.user.lastName} (${orgUser.user.username})`
+ : orgUser.user.email || orgUser.user.username
+ }));
+ }, [orgUsers, currentUsers]);
+
+ const {
+ control: addUserControl,
+ handleSubmit: handleAddUserSubmit,
+ reset: resetAddUserForm,
+ watch: watchAddUser,
+ formState: { errors: addUserErrors }
+ } = useForm<TAddUserForm>({
+ resolver: zodResolver(addUserFormSchema),
+ defaultValues: {
+ selectedUsers: [],
+ roles: []
+ }
+ });
+
+ const selectedUsersInModal = watchAddUser("selectedUsers");
+ const selectedRolesInModal = watchAddUser("roles");
+
+ const handleAddUsers = (form: TAddUserForm) => {
+ form.selectedUsers.forEach((user) => {
+ append({
+ username: user.value,
+ roles: form.roles.map((r) => r.slug)
+ });
+ });
+ resetAddUserForm();
+ setIsAddUserModalOpen(false);
+ };
+
+ const handleCloseAddUserModal = () => {
+ resetAddUserForm();
+ setIsAddUserModalOpen(false);
+ };
+
+ return (
+ <>
+ <form
+ onSubmit={handleSubmit(onFormSubmit)}
+ className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-7"
+ >
+ <div className="mb-8 flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-semibold tracking-normal">Project Members</h2>
+ <p className="mt-2 text-base text-mineshaft-300">
+ Add users who will be automatically added to projects created from this template.
+ </p>
+ </div>
+
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <div className="flex gap-3">
+ {isAllowed && isDirty && (
+ <>
+ <Button onClick={handleDiscard} variant="ghost" type="button" size="lg">
+ Discard
+ </Button>
+ <Button type="submit" variant="outline" size="lg">
+ <Save className="size-4" />
+ Save Changes
+ </Button>
+ </>
+ )}
+ <Button
+ onClick={() => setIsAddUserModalOpen(true)}
+ variant="project"
+ size="lg"
+ isDisabled={!isAllowed || availableOrgUsers.length === 0}
+ type="button"
+ >
+ <Plus className="size-4" />
+ Add User
+ </Button>
+ </div>
+ )}
+ </OrgPermissionCan>
+ </div>
+ {errors.users && <span className="my-4 text-sm text-red">{errors.users.message}</span>}
+ <Table
+ className="table-fixed"
+ containerClassName="rounded-lg border-mineshaft-600 bg-mineshaft-800"
+ >
+ <TableHeader>
+ <TableRow>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Username</TableHead>
+ <TableHead className="h-12 px-5 text-sm text-mineshaft-200">Roles</TableHead>
+ <TableHead className="h-12 w-20 px-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {users.length > 0 ? (
+ users.map(({ id }, pos) => (
+ <TableRow key={id} className="hover:bg-transparent">
+ <TableCell className="h-[58px] w-1/3 max-w-0 px-5 py-2">
+ <Controller
+ control={control}
+ name={`users.${pos}.username`}
+ render={({ field }) => (
+ <p className="truncate">
+ <span className="text-sm font-medium text-mineshaft-100">
+ {field.value}
+ </span>
+ </p>
+ )}
+ />
+ </TableCell>
+ <TableCell className="h-[58px] px-5 py-2">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Controller
+ control={control}
+ name={`users.${pos}.roles`}
+ render={({ field, fieldState: { error } }) => {
+ const availableRoleSlugs = new Set(availableRoles.map((r) => r.slug));
+ const orphanedRoles = field.value
+ .filter((slug) => !availableRoleSlugs.has(slug))
+ .map((slug) => ({ slug, name: slug }));
+ const allOptions = [...availableRoles, ...orphanedRoles];
+
+ const selectedValues = allOptions.filter((role) =>
+ field.value.includes(role.slug)
+ );
+
+ return (
+ <Field className="mb-0 max-w-[786px]">
+ <FilterableSelect
+ isMulti
+ isDisabled={!isAllowed}
+ options={allOptions}
+ value={selectedValues}
+ onChange={(selected) => {
+ field.onChange(
+ (selected as { slug: string; name: string }[]).map(
+ (s) => s.slug
+ )
+ );
+ }}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ menuPosition="fixed"
+ />
+ {error?.message && <FieldError>{error.message}</FieldError>}
+ </Field>
+ );
+ }}
+ />
+ )}
+ </OrgPermissionCan>
+ </TableCell>
+ <TableCell className="h-[58px] px-5 py-2">
+ <div className="flex justify-end">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={() => remove(pos)}
+ variant="ghost-muted"
+ size="xs"
+ aria-label="Remove user"
+ isDisabled={!isAllowed}
+ >
+ <Trash2 className="size-4" />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={3} className="h-24 p-0">
+ <Empty className="h-full rounded-none border-0 bg-mineshaft-800 p-6 md:p-8">
+ <EmptyHeader>
+ <EmptyTitle>No users assigned to this template</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </form>
+
+ <Dialog open={isAddUserModalOpen} onOpenChange={setIsAddUserModalOpen}>
+ <DialogContent className="max-w-xl overflow-visible">
+ <DialogHeader>
+ <DialogTitle>Add Users to Template</DialogTitle>
+ <DialogDescription>
+ Select users and roles to add to this project template
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleAddUserSubmit(handleAddUsers)}>
+ <div className="flex flex-col gap-4">
+ <Controller
+ control={addUserControl}
+ name="selectedUsers"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Select users</FieldLabel>
+ <FilterableSelect
+ isMulti
+ options={availableOrgUsers}
+ value={field.value}
+ onChange={field.onChange}
+ placeholder="Select one or more users..."
+ noOptionsMessage={() =>
+ availableOrgUsers.length === 0
+ ? "All organization members have been added"
+ : "No matching users found"
+ }
+ />
+ {addUserErrors.selectedUsers?.message && (
+ <FieldError>{addUserErrors.selectedUsers.message}</FieldError>
+ )}
+ </Field>
+ )}
+ />
+ <Controller
+ control={addUserControl}
+ name="roles"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Select roles</FieldLabel>
+ <FilterableSelect
+ isMulti
+ options={availableRoles}
+ value={field.value}
+ onChange={field.onChange}
+ getOptionValue={(option) => option.slug}
+ getOptionLabel={(option) => option.name}
+ placeholder="Select roles..."
+ />
+ {addUserErrors.roles?.message && (
+ <FieldError>{addUserErrors.roles.message}</FieldError>
+ )}
+ </Field>
+ )}
+ />
+ </div>
+ <div className="mt-8 flex items-center gap-4">
+ <Button
+ type="submit"
+ isDisabled={selectedUsersInModal.length === 0 || selectedRolesInModal.length === 0}
+ >
+ Add Users
+ </Button>
+ <Button type="button" variant="ghost" onClick={handleCloseAddUserModal}>
+ Cancel
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/index.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/index.tsx
new file mode 100644
index 0000000000..67f2cc9dba
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/components/index.tsx
@@ -0,0 +1,2 @@
+export * from "./EditProjectTemplate";
+export * from "./ProjectTemplateUsersSection";
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/index.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/index.tsx
new file mode 100644
index 0000000000..cd6925f94c
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/EditProjectTemplateSection/index.tsx
@@ -0,0 +1 @@
+export * from "./EditProjectTemplateSection";
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplateDetailsModal.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplateDetailsModal.tsx
new file mode 100644
index 0000000000..3612157546
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplateDetailsModal.tsx
@@ -0,0 +1,143 @@
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ TextArea
+} from "@app/components/v3";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import {
+ TProjectTemplate,
+ useCreateProjectTemplate,
+ useUpdateProjectTemplate
+} from "@app/hooks/api/projectTemplates";
+import { slugSchema } from "@app/lib/schemas";
+
+const formSchema = z.object({
+ name: slugSchema({ min: 1, max: 64, field: "Name" }),
+ description: z.string().max(500).optional(),
+ type: z.nativeEnum(ProjectType).default(ProjectType.SecretManager)
+});
+
+export type FormData = z.infer<typeof formSchema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ onComplete?: (template: TProjectTemplate) => void;
+ projectTemplate?: TProjectTemplate;
+};
+
+type FormProps = {
+ projectTemplate?: TProjectTemplate;
+ onComplete: (template: TProjectTemplate) => void;
+};
+
+const ProjectTemplateForm = ({ onComplete, projectTemplate }: FormProps) => {
+ const createProjectTemplate = useCreateProjectTemplate();
+ const updateProjectTemplate = useUpdateProjectTemplate();
+
+ const {
+ handleSubmit,
+ register,
+ formState: { isSubmitting, errors }
+ } = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: projectTemplate?.name,
+ description: projectTemplate?.description,
+ type: projectTemplate?.type ?? ProjectType.SecretManager
+ }
+ });
+
+ const onFormSubmit = async (data: FormData) => {
+ const mutation = projectTemplate
+ ? updateProjectTemplate.mutateAsync({
+ templateId: projectTemplate.id,
+ name: data.name,
+ description: data.description
+ })
+ : createProjectTemplate.mutateAsync({ ...data });
+
+ const template = await mutation;
+ createNotification({
+ text: `Successfully ${
+ projectTemplate ? "updated template details" : "created project template"
+ }`,
+ type: "success"
+ });
+
+ onComplete(template);
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onFormSubmit)}>
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <Input autoFocus placeholder="my-project-template" {...register("name")} />
+ <FieldDescription>Name must be slug-friendly</FieldDescription>
+ {errors.name?.message && <FieldError>{errors.name.message}</FieldError>}
+ </Field>
+ <Field className="mt-4">
+ <FieldLabel>Description (optional)</FieldLabel>
+ <TextArea
+ className="max-h-80 min-h-40 max-w-full min-w-full"
+ {...register("description")}
+ />
+ {errors.description?.message && <FieldError>{errors.description.message}</FieldError>}
+ </Field>
+ <div className="mt-4 flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ isPending={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ {projectTemplate ? "Update" : "Add"} Template
+ </Button>
+ <DialogClose asChild>
+ <Button variant="ghost">Cancel</Button>
+ </DialogClose>
+ </div>
+ </form>
+ );
+};
+
+export const ProjectTemplateDetailsModal = ({
+ isOpen,
+ onOpenChange,
+ projectTemplate,
+ onComplete
+}: Props) => {
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>
+ {projectTemplate ? "Edit Project Template Details" : "Create Project Template"}
+ </DialogTitle>
+ </DialogHeader>
+ <ProjectTemplateForm
+ projectTemplate={projectTemplate}
+ onComplete={(template) => {
+ if (onComplete) onComplete(template);
+ onOpenChange(false);
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplatesSection.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplatesSection.tsx
new file mode 100644
index 0000000000..fbaa4141c9
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplatesSection.tsx
@@ -0,0 +1,93 @@
+import { useState } from "react";
+import { LayoutTemplate } from "lucide-react";
+
+import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useSubscription } from "@app/context";
+import { TProjectTemplate } from "@app/hooks/api/projectTemplates";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+import { EditProjectTemplateSection } from "./EditProjectTemplateSection";
+import { ProjectTemplateDetailsModal } from "./ProjectTemplateDetailsModal";
+import { ProjectTemplatesTable } from "./ProjectTemplatesTable";
+
+export const ProjectTemplatesSection = () => {
+ const { subscription } = useSubscription();
+ const [editTemplate, setEditTemplate] = useState<TProjectTemplate | null>(null);
+
+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
+ "upgradePlan",
+ "addTemplate"
+ ] as const);
+
+ if (editTemplate) {
+ return (
+ <EditProjectTemplateSection template={editTemplate} onBack={() => setEditTemplate(null)} />
+ );
+ }
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <LayoutTemplate className="size-4 text-accent" />
+ Project Templates
+ </CardTitle>
+ <CardDescription>
+ Create and configure templates with predefined roles and environments to streamline
+ project setup.
+ </CardDescription>
+ <CardAction>
+ <OrgPermissionCan
+ I={OrgPermissionActions.Create}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <Button
+ variant="project"
+ isDisabled={!isAllowed}
+ onClick={() => {
+ if (!subscription?.projectTemplates) {
+ handlePopUpOpen("upgradePlan", {
+ isEnterpriseFeature: true
+ });
+ return;
+ }
+
+ handlePopUpOpen("addTemplate");
+ }}
+ >
+ Add Template
+ </Button>
+ )}
+ </OrgPermissionCan>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <ProjectTemplatesTable onEdit={setEditTemplate} />
+ </CardContent>
+ </Card>
+ <ProjectTemplateDetailsModal
+ onComplete={(template) => setEditTemplate(template)}
+ isOpen={popUp.addTemplate.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("addTemplate", isOpen)}
+ />
+ <UpgradePlanModal
+ isOpen={popUp.upgradePlan.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
+ text="Your current plan does not include access to project templates. To unlock this feature, please upgrade to Infisical Enterprise plan."
+ isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplatesTable.tsx b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplatesTable.tsx
new file mode 100644
index 0000000000..8d781c200f
--- /dev/null
+++ b/frontend/src/pages/organization/ProductSettingsPage/SecretsManagement/project-templates/ProjectTemplatesTable.tsx
@@ -0,0 +1,278 @@
+import { useMemo, useState } from "react";
+import { faCircleInfo, faMagnifyingGlass, faTrash } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ Empty,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { OrgPermissionActions, OrgPermissionSubjects, useSubscription } from "@app/context";
+import { usePopUp } from "@app/hooks";
+import { TProjectTemplate, useListProjectTemplates } from "@app/hooks/api/projectTemplates";
+
+import { DeleteProjectTemplateModal } from "./DeleteProjectTemplateModal";
+
+type Props = {
+ onEdit: (projectTemplate: TProjectTemplate) => void;
+};
+
+const skeletonRowIds = [
+ "template-skeleton-1",
+ "template-skeleton-2",
+ "template-skeleton-3",
+ "template-skeleton-4",
+ "template-skeleton-5"
+];
+
+const tableColumnKeys = ["name", "roles", "users", "groups", "identities", "actions"];
+
+export const ProjectTemplatesTable = ({ onEdit }: Props) => {
+ const { subscription } = useSubscription();
+
+ const { isPending, data: projectTemplates = [] } = useListProjectTemplates({
+ enabled: subscription?.projectTemplates
+ });
+
+ const [search, setSearch] = useState("");
+
+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["deleteTemplate"] as const);
+
+ const filteredTemplates = useMemo(
+ () =>
+ projectTemplates?.filter(
+ (template) =>
+ template.name !== "default" &&
+ template.name.toLowerCase().includes(search.toLowerCase().trim())
+ ) ?? [],
+ [search, projectTemplates]
+ );
+
+ const colSpan = tableColumnKeys.length;
+
+ return (
+ <div>
+ <InputGroup>
+ <InputGroupAddon>
+ <FontAwesomeIcon icon={faMagnifyingGlass} />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search templates..."
+ />
+ </InputGroup>
+ <Table className="mt-4">
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Roles</TableHead>
+ <TableHead>Users</TableHead>
+ <TableHead>Groups</TableHead>
+ <TableHead>Machine Identities</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {subscription?.projectTemplates &&
+ isPending &&
+ skeletonRowIds.map((rowId) => (
+ <TableRow key={rowId}>
+ {tableColumnKeys.map((columnKey) => (
+ <TableCell key={`${rowId}-${columnKey}`}>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ {filteredTemplates.map((template) => {
+ const {
+ id,
+ name,
+ roles,
+ description,
+ users,
+ groups,
+ identities,
+ projectManagedIdentities
+ } = template;
+
+ const totalIdentities =
+ (identities?.length || 0) + (projectManagedIdentities?.length || 0);
+
+ return (
+ <TableRow
+ onClick={() => onEdit(template)}
+ className="cursor-pointer hover:bg-mineshaft-700"
+ key={id}
+ >
+ <TableCell>
+ {name}
+ {description && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <FontAwesomeIcon
+ size="sm"
+ className="ml-2 text-mineshaft-400"
+ icon={faCircleInfo}
+ />
+ </TooltipTrigger>
+ <TooltipContent>{description}</TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ <TableCell className="pl-8">
+ {roles.length}
+ {roles.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <FontAwesomeIcon
+ size="sm"
+ className="ml-2 text-mineshaft-400"
+ icon={faCircleInfo}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <ul className="ml-2 list-disc">
+ {roles.map((role) => (
+ <li key={role.name}>{role.name}</li>
+ ))}
+ </ul>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ <TableCell className="pl-8">
+ {users?.length || 0}
+ {users && Boolean(users.length) && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <FontAwesomeIcon
+ size="sm"
+ className="ml-2 text-mineshaft-400"
+ icon={faCircleInfo}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <ul className="ml-2 list-disc">
+ {users.map((user) => (
+ <li key={user.username}>{user.username}</li>
+ ))}
+ </ul>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ <TableCell className="pl-8">
+ {groups?.length || 0}
+ {groups && Boolean(groups.length) && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <FontAwesomeIcon
+ size="sm"
+ className="ml-2 text-mineshaft-400"
+ icon={faCircleInfo}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <ul className="ml-2 list-disc">
+ {groups.map((group) => (
+ <li key={group.groupSlug}>{group.groupSlug}</li>
+ ))}
+ </ul>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ <TableCell className="pl-8">
+ {totalIdentities}
+ {Boolean(totalIdentities) && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <FontAwesomeIcon
+ size="sm"
+ className="ml-2 text-mineshaft-400"
+ icon={faCircleInfo}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ <ul className="ml-2 list-disc">
+ {(projectManagedIdentities || []).map((identity) => (
+ <li key={identity.name}>{identity.name}</li>
+ ))}
+ {identities && Boolean(identities?.length) && (
+ <li key="org">
+ {identities.length} Organization Identit
+ {identities.length === 1 ? "y" : "ies"}
+ </li>
+ )}
+ </ul>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ <TableCell className="w-5">
+ {name !== "default" && (
+ <OrgPermissionCan
+ I={OrgPermissionActions.Delete}
+ a={OrgPermissionSubjects.ProjectTemplates}
+ >
+ {(isAllowed) => (
+ <IconButton
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("deleteTemplate", template);
+ }}
+ variant="ghost"
+ aria-label="Delete template"
+ isDisabled={!isAllowed}
+ >
+ <FontAwesomeIcon icon={faTrash} />
+ </IconButton>
+ )}
+ </OrgPermissionCan>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ {(!subscription?.projectTemplates || (!isPending && filteredTemplates?.length === 0)) && (
+ <TableRow>
+ <TableCell colSpan={colSpan}>
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>
+ {search.trim()
+ ? "No project templates match search"
+ : "No project templates found"}
+ </EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ <DeleteProjectTemplateModal
+ isOpen={popUp.deleteTemplate.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("deleteTemplate", isOpen)}
+ template={popUp.deleteTemplate.data}
+ />
+ </div>
+ );
+};