Skip to content

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

feat(ui): updated ui with identity privilege hooks and new role form

Akhil Mohan64e868a151bd
diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.ts
index b8829f798a..4ac19c3511 100644
--- a/frontend/src/hooks/api/identities/types.ts
+++ b/frontend/src/hooks/api/identities/types.ts
@@ -29,30 +29,30 @@ export type IdentityMembershipOrg = {
export type IdentityMembership = {
id: string;
identity: Identity;
- roles: {
- id: string;
- role: "owner" | "admin" | "member" | "no-access" | "custom";
- customRoleId: string;
- customRoleName: string;
- customRoleSlug: string;
- isTemporary: boolean;
- temporaryMode: string | null;
- temporaryRange: string | null;
- temporaryAccessStartTime: string | null;
- temporaryAccessEndTime: string | null;
- }[];
- additionalPrivileges: {
- id: string;
- name: string;
- description: string | null | undefined;
- slug: string;
- temporaryRange: string | null | undefined;
- temporaryMode: string | null | undefined;
- temporaryAccessEndTime: string | null | undefined;
- temporaryAccessStartTime: string | null | undefined;
- isTemporary: boolean;
- createdAt: string;
- }[];
+ roles: Array<
+ {
+ id: string;
+ role: "owner" | "admin" | "member" | "no-access" | "custom";
+ customRoleId: string;
+ customRoleName: string;
+ customRoleSlug: string;
+ } & (
+ | {
+ isTemporary: false;
+ temporaryRange: null;
+ temporaryMode: null;
+ temporaryAccessEndTime: null;
+ temporaryAccessStartTime: null;
+ }
+ | {
+ isTemporary: true;
+ temporaryRange: string;
+ temporaryMode: string;
+ temporaryAccessEndTime: string;
+ temporaryAccessStartTime: string;
+ }
+ )
+ >;
createdAt: string;
updatedAt: string;
};
diff --git a/frontend/src/hooks/api/identityProjectAdditionalPrivilege/mutation.tsx b/frontend/src/hooks/api/identityProjectAdditionalPrivilege/mutation.tsx
index 420d29485d..d9a2a0b0a1 100644
--- a/frontend/src/hooks/api/identityProjectAdditionalPrivilege/mutation.tsx
+++ b/frontend/src/hooks/api/identityProjectAdditionalPrivilege/mutation.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace/queries";
+import { identitiyProjectPrivilegeKeys } from "./queries";
import {
TCreateIdentityProjectPrivilegeDTO,
TDeleteIdentityProjectPrivilegeDTO,
@@ -14,20 +14,19 @@ import {
export const useCreateIdentityProjectAdditionalPrivilege = () => {
const queryClient = useQueryClient();
- return useMutation<
- { privilege: TIdentityProjectPrivilege },
- {},
- TCreateIdentityProjectPrivilegeDTO
- >({
+ return useMutation<TIdentityProjectPrivilege, {}, TCreateIdentityProjectPrivilegeDTO>({
mutationFn: async (dto) => {
const { data } = await apiRequest.post("/api/v1/additional-privilege/identity", {
...dto,
+ isPackedPermission: true,
permissions: packRules(dto.permissions)
});
return data.privilege;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries(workspaceKeys.getWorkspaceIdentityMemberships(projectId));
+ onSuccess: (_, { projectSlug, identityId }) => {
+ queryClient.invalidateQueries(
+ identitiyProjectPrivilegeKeys.list({ projectSlug, identityId })
+ );
}
});
};
@@ -35,20 +34,24 @@ export const useCreateIdentityProjectAdditionalPrivilege = () => {
export const useUpdateIdentityProjectAdditionalPrivilege = () => {
const queryClient = useQueryClient();
- return useMutation<
- { privilege: TIdentityProjectPrivilege },
- {},
- TUpdateIdentityProjectPrivlegeDTO
- >({
- mutationFn: async (dto) => {
- const { data } = await apiRequest.patch(
- `/api/v1/additional-privilege/identity/${dto.privilegeId}`,
- { ...dto, permissions: dto.permissions ? packRules(dto.permissions) : undefined }
- );
- return data.privilege;
+ return useMutation<TIdentityProjectPrivilege, {}, TUpdateIdentityProjectPrivlegeDTO>({
+ mutationFn: async ({ slug, projectSlug, identityId, data }) => {
+ const { data: res } = await apiRequest.patch("/api/v1/additional-privilege/identity", {
+ slug,
+ projectSlug,
+ identityId,
+ data: {
+ isPackedPermission: true,
+ ...data,
+ permissions: data.permissions ? packRules(data.permissions) : undefined
+ }
+ });
+ return res.privilege;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries(workspaceKeys.getWorkspaceIdentityMemberships(projectId));
+ onSuccess: (_, { projectSlug, identityId }) => {
+ queryClient.invalidateQueries(
+ identitiyProjectPrivilegeKeys.list({ projectSlug, identityId })
+ );
}
});
};
@@ -56,19 +59,21 @@ export const useUpdateIdentityProjectAdditionalPrivilege = () => {
export const useDeleteIdentityProjectAdditionalPrivilege = () => {
const queryClient = useQueryClient();
- return useMutation<
- { privilege: TIdentityProjectPrivilege },
- {},
- TDeleteIdentityProjectPrivilegeDTO
- >({
- mutationFn: async (dto) => {
- const { data } = await apiRequest.delete(
- `/api/v1/additional-privilege/identity/${dto.privilegeId}`
- );
+ return useMutation<TIdentityProjectPrivilege, {}, TDeleteIdentityProjectPrivilegeDTO>({
+ mutationFn: async ({ identityId, projectSlug, slug }) => {
+ const { data } = await apiRequest.delete("/api/v1/additional-privilege/identity", {
+ data: {
+ identityId,
+ projectSlug,
+ slug
+ }
+ });
return data.privilege;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries(workspaceKeys.getWorkspaceIdentityMemberships(projectId));
+ onSuccess: (_, { projectSlug, identityId }) => {
+ queryClient.invalidateQueries(
+ identitiyProjectPrivilegeKeys.list({ projectSlug, identityId })
+ );
}
});
};
diff --git a/frontend/src/hooks/api/identityProjectAdditionalPrivilege/queries.tsx b/frontend/src/hooks/api/identityProjectAdditionalPrivilege/queries.tsx
index 2bbd71c702..8ad60ba6c7 100644
--- a/frontend/src/hooks/api/identityProjectAdditionalPrivilege/queries.tsx
+++ b/frontend/src/hooks/api/identityProjectAdditionalPrivilege/queries.tsx
@@ -4,28 +4,74 @@ import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TProjectPermission } from "../roles/types";
-import { TIdentityProjectPrivilege } from "./types";
+import {
+ TGetIdentityProejctPrivilegeDetails as TGetIdentityProjectPrivilegeDetails,
+ TIdentityProjectPrivilege,
+ TListIdentityUserPrivileges as TListIdentityProjectPrivileges
+} from "./types";
export const identitiyProjectPrivilegeKeys = {
- details: (privilegeId: string) => ["project-user-privilege", { privilegeId }] as const
+ details: ({ identityId, slug, projectSlug }: TGetIdentityProjectPrivilegeDetails) =>
+ [
+ "identity-user-privilege",
+ {
+ identityId,
+ projectSlug,
+ slug
+ }
+ ] as const,
+ list: ({ projectSlug, identityId }: TListIdentityProjectPrivileges) =>
+ ["identity-user-privileges", { identityId, projectSlug }] as const
};
-const fetchIdentityProjectPrivilegeDetails = async (privilegeId: string) => {
- const {
- data: { privilege }
- } = await apiRequest.get<{
- privilege: Omit<TIdentityProjectPrivilege, "permissions"> & { permissions: unknown };
- }>(`/api/v1/additional-privilege/identity/${privilegeId}`);
- return {
- ...privilege,
- permissions: unpackRules(privilege.permissions as PackRule<TProjectPermission>[])
- };
+export const useGetIdentityProjectPrivilegeDetails = ({
+ projectSlug,
+ identityId,
+ slug
+}: TGetIdentityProjectPrivilegeDetails) => {
+ return useQuery({
+ enabled: Boolean(projectSlug && identityId && slug),
+ queryKey: identitiyProjectPrivilegeKeys.details({ projectSlug, slug, identityId }),
+ queryFn: async () => {
+ const {
+ data: { privilege }
+ } = await apiRequest.get<{
+ privilege: Omit<TIdentityProjectPrivilege, "permissions"> & { permissions: unknown };
+ }>(`/api/v1/additional-privilege/identity/${slug}`, {
+ params: {
+ identityId,
+ projectSlug
+ }
+ });
+ return {
+ ...privilege,
+ permissions: unpackRules(privilege.permissions as PackRule<TProjectPermission>[])
+ };
+ }
+ });
};
-export const useGetIdentityProjectPrivilegeDetails = (privilegeId: string) => {
+export const useListIdentityProjectPrivileges = ({
+ projectSlug,
+ identityId
+}: TListIdentityProjectPrivileges) => {
return useQuery({
- enabled: Boolean(privilegeId),
- queryKey: identitiyProjectPrivilegeKeys.details(privilegeId),
- queryFn: () => fetchIdentityProjectPrivilegeDetails(privilegeId)
+ enabled: Boolean(projectSlug && identityId),
+ queryKey: identitiyProjectPrivilegeKeys.list({ projectSlug, identityId }),
+ queryFn: async () => {
+ const {
+ data: { privileges }
+ } = await apiRequest.get<{
+ privileges: Array<
+ Omit<TIdentityProjectPrivilege, "permissions"> & { permissions: unknown }
+ >;
+ }>("/api/v1/additional-privilege/identity", {
+ params: { identityId, projectSlug, unpacked: false }
+ });
+ return privileges.map((el) => ({
+ ...el,
+ permissions: unpackRules(el.permissions as PackRule<TProjectPermission>[])
+ }));
+ }
});
};
diff --git a/frontend/src/hooks/api/identityProjectAdditionalPrivilege/types.tsx b/frontend/src/hooks/api/identityProjectAdditionalPrivilege/types.tsx
index 3362e3301f..1e07db5978 100644
--- a/frontend/src/hooks/api/identityProjectAdditionalPrivilege/types.tsx
+++ b/frontend/src/hooks/api/identityProjectAdditionalPrivilege/types.tsx
@@ -7,25 +7,31 @@ export enum IdentityProjectAdditionalPrivilegeTemporaryMode {
export type TIdentityProjectPrivilege = {
projectMembershipId: string;
slug: string;
- name: string;
- isTemporary: boolean;
id: string;
createdAt: Date;
updatedAt: Date;
- description?: string | null | undefined;
- temporaryMode?: string | null | undefined;
- temporaryRange?: string | null | undefined;
- temporaryAccessStartTime?: string | null | undefined;
- temporaryAccessEndTime?: Date | null | undefined;
permissions?: TProjectPermission[];
-};
+} & (
+ | {
+ isTemporary: true;
+ temporaryMode: string;
+ temporaryRange: string;
+ temporaryAccessStartTime: string;
+ temporaryAccessEndTime?: string;
+ }
+ | {
+ isTemporary: false;
+ temporaryMode?: null;
+ temporaryRange?: null;
+ temporaryAccessStartTime?: null;
+ temporaryAccessEndTime?: null;
+ }
+ );
export type TCreateIdentityProjectPrivilegeDTO = {
identityId: string;
- projectId: string;
- slug: string;
- name: string;
- description?: string;
+ projectSlug: string;
+ slug?: string;
isTemporary?: boolean;
temporaryMode?: IdentityProjectAdditionalPrivilegeTemporaryMode;
temporaryRange?: string;
@@ -34,15 +40,25 @@ export type TCreateIdentityProjectPrivilegeDTO = {
};
export type TUpdateIdentityProjectPrivlegeDTO = {
- privilegeId: string;
- projectId: string;
-} & Partial<Omit<TCreateIdentityProjectPrivilegeDTO, "projectMembershipId" | "projectId">>;
+ projectSlug: string;
+ identityId: string;
+ slug: string;
+ data: Partial<Omit<TCreateIdentityProjectPrivilegeDTO, "projectMembershipId" | "projectId">>;
+};
export type TDeleteIdentityProjectPrivilegeDTO = {
- privilegeId: string;
- projectId: string;
+ projectSlug: string;
+ identityId: string;
+ slug: string;
+};
+
+export type TListIdentityUserPrivileges = {
+ projectSlug: string;
+ identityId: string;
};
export type TGetIdentityProejctPrivilegeDetails = {
- privilegeId: string;
+ projectSlug: string;
+ identityId: string;
+ slug: string;
};
diff --git a/frontend/src/views/Project/MembersPage/components/IdentityTab/IdentityTab.tsx b/frontend/src/views/Project/MembersPage/components/IdentityTab/IdentityTab.tsx
index 816d786ed9..d82c53d2a6 100644
--- a/frontend/src/views/Project/MembersPage/components/IdentityTab/IdentityTab.tsx
+++ b/frontend/src/views/Project/MembersPage/components/IdentityTab/IdentityTab.tsx
@@ -1,6 +1,8 @@
import Link from "next/link";
import {
faArrowUpRightFromSquare,
+ faClock,
+ faEdit,
faPlus,
faServer,
faXmark
@@ -8,6 +10,7 @@ import {
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { format } from "date-fns";
import { motion } from "framer-motion";
+import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
@@ -15,23 +18,39 @@ import {
Button,
DeleteActionModal,
EmptyState,
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
IconButton,
+ Modal,
+ ModalContent,
Table,
TableContainer,
TableSkeleton,
+ Tag,
TBody,
Td,
Th,
THead,
+ Tooltip,
Tr
} from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
import { withProjectPermission } from "@app/hoc";
import { useDeleteIdentityFromWorkspace, useGetWorkspaceIdentityMemberships } from "@app/hooks/api";
+import { IdentityMembership } from "@app/hooks/api/identities/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { usePopUp } from "@app/hooks/usePopUp";
import { IdentityModal } from "./components/IdentityModal";
+import { IdentityRoleForm } from "./components/IdentityRoleForm";
+const MAX_ROLES_TO_BE_SHOWN_IN_TABLE = 2;
+const formatRoleName = (role: string, customRoleName?: string) => {
+ if (role === ProjectMembershipRole.Custom) return customRoleName;
+ if (role === ProjectMembershipRole.Member) return "Developer";
+ return role;
+};
export const IdentityTab = withProjectPermission(
() => {
const { currentWorkspace } = useWorkspace();
@@ -45,7 +64,7 @@ export const IdentityTab = withProjectPermission(
"identity",
"deleteIdentity",
"upgradePlan",
- "additionalPrivilege"
+ "updateRole"
] as const);
const onRemoveIdentitySubmit = async (identityId: string) => {
@@ -75,7 +94,7 @@ export const IdentityTab = withProjectPermission(
return (
<motion.div
- key="panel-identity"
+ key="identity-role-panel"
transition={{ duration: 0.15 }}
initial={{ opacity: 0, translateX: 30 }}
animate={{ opacity: 1, translateX: 0 }}
@@ -127,10 +146,121 @@ export const IdentityTab = withProjectPermission(
{!isLoading &&
data &&
data.length > 0 &&
- data.map(({ identity: { id, name }, createdAt }) => {
+ data.map((identityMember, index) => {
+ const {
+ identity: { id, name },
+ roles,
+ createdAt
+ } = identityMember;
return (
<Tr className="h-10" key={`st-v3-${id}`}>
<Td>{name}</Td>
+
+ <Td>
+ <div className="flex items-center space-x-2">
+ {roles
+ .slice(0, MAX_ROLES_TO_BE_SHOWN_IN_TABLE)
+ .map(
+ ({
+ role,
+ customRoleName,
+ id: roleId,
+ isTemporary,
+ temporaryAccessEndTime
+ }) => {
+ const isExpired =
+ new Date() > new Date(temporaryAccessEndTime || ("" as string));
+ return (
+ <Tag key={roleId}>
+ <div className="flex items-center space-x-2">
+ <div>{formatRoleName(role, customRoleName)}</div>
+ {isTemporary && (
+ <div>
+ <Tooltip
+ content={
+ isExpired
+ ? "Timed role expired"
+ : "Timed role access"
+ }
+ >
+ <FontAwesomeIcon
+ icon={faClock}
+ className={twMerge(isExpired && "text-red-600")}
+ />
+ </Tooltip>
+ </div>
+ )}
+ </div>
+ </Tag>
+ );
+ }
+ )}
+ {roles.length > MAX_ROLES_TO_BE_SHOWN_IN_TABLE && (
+ <HoverCard>
+ <HoverCardTrigger>
+ <Tag>+{roles.length - MAX_ROLES_TO_BE_SHOWN_IN_TABLE}</Tag>
+ </HoverCardTrigger>
+ <HoverCardContent className="border border-gray-700 bg-mineshaft-800 p-4">
+ {roles
+ .slice(MAX_ROLES_TO_BE_SHOWN_IN_TABLE)
+ .map(
+ ({
+ role,
+ customRoleName,
+ id: roleId,
+ isTemporary,
+ temporaryAccessEndTime
+ }) => {
+ const isExpired =
+ new Date() >
+ new Date(temporaryAccessEndTime || ("" as string));
+ return (
+ <Tag key={roleId} className="capitalize">
+ <div className="flex items-center space-x-2">
+ <div>{formatRoleName(role, customRoleName)}</div>
+ {isTemporary && (
+ <div>
+ <Tooltip
+ content={
+ isExpired
+ ? "Access expired"
+ : "Temporary access"
+ }
+ >
+ <FontAwesomeIcon
+ icon={faClock}
+ className={twMerge(
+ new Date() >
+ new Date(
+ temporaryAccessEndTime as string
+ ) && "text-red-600"
+ )}
+ />
+ </Tooltip>
+ </div>
+ )}
+ </div>
+ </Tag>
+ );
+ }
+ )}
+ </HoverCardContent>
+ </HoverCard>
+ )}
+ <Tooltip content="Edit permission">
+ <IconButton
+ size="sm"
+ variant="plain"
+ ariaLabel="update-role"
+ onClick={() =>
+ handlePopUpOpen("updateRole", { ...identityMember, index })
+ }
+ >
+ <FontAwesomeIcon icon={faEdit} />
+ </IconButton>
+ </Tooltip>
+ </div>
+ </Td>
<Td>{format(new Date(createdAt), "yyyy-MM-dd")}</Td>
<Td className="flex justify-end">
<ProjectPermissionCan
@@ -173,7 +303,30 @@ export const IdentityTab = withProjectPermission(
</TBody>
</Table>
</TableContainer>
-
+ <Modal
+ isOpen={popUp.updateRole.isOpen}
+ onOpenChange={(state) => handlePopUpToggle("updateRole", state)}
+ >
+ <ModalContent
+ className="max-w-4xl"
+ title={`Manage Access for ${(popUp.updateRole.data as IdentityMembership)?.identity?.name
+ }`}
+ subTitle={`
+Configure role-based access control by Infisical users a mix of one built-in role, multiple custom roles, and multiple specific privileges. A user will gain access to alll actions within the roles assigned to them, not just the actions those roles share in common. You must choose at least one permanent role.
+`}
+ >
+ <IdentityRoleForm
+ onOpenUpgradeModal={(description) =>
+ handlePopUpOpen("upgradePlan", { description })
+ }
+ identityProjectMember={
+ data?.[
+ (popUp.updateRole?.data as IdentityMembership & { index: number })?.index
+ ] as IdentityMembership
+ }
+ />
+ </ModalContent>
+ </Modal>
<IdentityModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<DeleteActionModal
isOpen={popUp.deleteIdentity.isOpen}
diff --git a/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/IdentityRbacSection.tsx b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/IdentityRbacSection.tsx
new file mode 100644
index 0000000000..9d25c7ed07
--- /dev/null
+++ b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/IdentityRbacSection.tsx
@@ -0,0 +1,341 @@
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { faCaretDown, faClock, faClose } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { formatDistance } from "date-fns";
+import ms from "ms";
+import { twMerge } from "tailwind-merge";
+import { z } from "zod";
+
+import { TtlFormLabel } from "@app/components/features";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ FormControl,
+ IconButton,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Select,
+ SelectItem,
+ Spinner,
+ Tag,
+ Tooltip
+} from "@app/components/v2";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSub,
+ useProjectPermission,
+ useSubscription,
+ useWorkspace
+} from "@app/context";
+import { useGetProjectRoles, useUpdateIdentityWorkspaceRole } from "@app/hooks/api";
+import { IdentityMembership } from "@app/hooks/api/identities/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/workspace/types";
+
+const roleFormSchema = z.object({
+ roles: z
+ .object({
+ slug: z.string(),
+ temporaryAccess: z.discriminatedUnion("isTemporary", [
+ z.object({
+ isTemporary: z.literal(true),
+ temporaryRange: z.string().min(1),
+ temporaryAccessStartTime: z.string().datetime(),
+ temporaryAccessEndTime: z.string().datetime().nullable().optional()
+ }),
+ z.object({
+ isTemporary: z.literal(false)
+ })
+ ])
+ })
+ .array()
+});
+type TRoleForm = z.infer<typeof roleFormSchema>;
+
+type Props = {
+ identityProjectMember: IdentityMembership;
+ onOpenUpgradeModal: (title: string) => void;
+};
+export const IdentityRbacSection = ({ identityProjectMember, onOpenUpgradeModal }: Props) => {
+ const { subscription } = useSubscription();
+ const { currentWorkspace } = useWorkspace();
+ const workspaceId = currentWorkspace?.id || "";
+ const { data: projectRoles, isLoading: isRolesLoading } = useGetProjectRoles(workspaceId);
+ const { permission } = useProjectPermission();
+ const isMemberEditDisabled = permission.cannot(
+ ProjectPermissionActions.Edit,
+ ProjectPermissionSub.Identity
+ );
+
+ const roleForm = useForm<TRoleForm>({
+ resolver: zodResolver(roleFormSchema),
+ values: {
+ roles: identityProjectMember?.roles?.map(({ customRoleSlug, role, ...dto }) => ({
+ slug: customRoleSlug || role,
+ temporaryAccess: dto.isTemporary
+ ? {
+ isTemporary: true,
+ temporaryRange: dto.temporaryRange,
+ temporaryAccessEndTime: dto.temporaryAccessEndTime,
+ temporaryAccessStartTime: dto.temporaryAccessStartTime
+ }
+ : {
+ isTemporary: dto.isTemporary
+ }
+ }))
+ }
+ });
+ const selectedRoleList = useFieldArray({
+ name: "roles",
+ control: roleForm.control
+ });
+
+ const formRoleField = roleForm.watch("roles");
+
+ const updateMembershipRole = useUpdateIdentityWorkspaceRole();
+
+ const handleRoleUpdate = async (data: TRoleForm) => {
+ if (updateMembershipRole.isLoading) return;
+
+ const sanitizedRoles = data.roles.map((el) => {
+ const { isTemporary } = el.temporaryAccess;
+ if (!isTemporary) {
+ return { role: el.slug, isTemporary: false as const };
+ }
+ return {
+ role: el.slug,
+ isTemporary: true as const,
+ temporaryMode: ProjectUserMembershipTemporaryMode.Relative,
+ temporaryRange: el.temporaryAccess.temporaryRange,
+ temporaryAccessStartTime: el.temporaryAccess.temporaryAccessStartTime
+ };
+ });
+
+ const hasCustomRoleSelected = sanitizedRoles.some(
+ (el) => !Object.values(ProjectMembershipRole).includes(el.role as ProjectMembershipRole)
+ );
+
+ if (hasCustomRoleSelected && subscription && !subscription?.rbac) {
+ onOpenUpgradeModal(
+ "You can assign custom roles to members if you upgrade your Infisical plan."
+ );
+ return;
+ }
+
+ try {
+ await updateMembershipRole.mutateAsync({
+ workspaceId,
+ identityId: identityProjectMember.identity.id,
+ roles: sanitizedRoles
+ });
+ createNotification({ text: "Successfully updated roles", type: "success" });
+ roleForm.reset(undefined, { keepValues: true });
+ } catch (err) {
+ createNotification({ text: "Failed to update role", type: "error" });
+ }
+ };
+
+ if (isRolesLoading)
+ return (
+ <div className="flex w-full items-center justify-center p-8">
+ <Spinner />
+ </div>
+ );
+
+ return (
+ <div>
+ <div className="text-lg font-medium">Roles</div>
+ <p className="text-sm text-mineshaft-400">Select one of the pre-defined or custom roles.</p>
+ <div>
+ <form onSubmit={roleForm.handleSubmit(handleRoleUpdate)}>
+ <div className="mt-2 flex flex-col space-y-2">
+ {selectedRoleList.fields.map(({ id }, index) => {
+ const { temporaryAccess } = formRoleField[index];
+ const isTemporary = temporaryAccess?.isTemporary;
+ const isExpired =
+ temporaryAccess.isTemporary &&
+ new Date() > new Date(temporaryAccess.temporaryAccessEndTime || "");
+
+ return (
+ <div key={id} className="flex items-center space-x-2">
+ <Controller
+ control={roleForm.control}
+ name={`roles.${index}.slug`}
+ render={({ field: { onChange, ...field } }) => (
+ <Select
+ defaultValue={field.value}
+ {...field}
+ isDisabled={isMemberEditDisabled}
+ onValueChange={(e) => onChange(e)}
+ className="w-full bg-mineshaft-600"
+ >
+ {projectRoles?.map(({ name, slug, id: projectRoleId }) => (
+ <SelectItem value={slug} key={projectRoleId}>
+ {name}
+ </SelectItem>
+ ))}
+ </Select>
+ )}
+ />
+ <Popover>
+ <PopoverTrigger disabled={isMemberEditDisabled}>
+ <Tooltip
+ asChild
+ content={isExpired ? "Timed access expired" : "Grant timed access"}
+ >
+ <Button
+ variant="outline_bg"
+ leftIcon={isTemporary ? <FontAwesomeIcon icon={faClock} /> : undefined}
+ rightIcon={<FontAwesomeIcon icon={faCaretDown} className="ml-2" />}
+ isDisabled={isMemberEditDisabled}
+ className={twMerge(
+ "border-none bg-mineshaft-600 py-2 capitalize",
+ isTemporary && "text-primary",
+ isExpired && "text-red-600"
+ )}
+ >
+ {!temporaryAccess?.isTemporary
+ ? "Permanent"
+ : formatDistance(
+ new Date(temporaryAccess.temporaryAccessEndTime || ""),
+ new Date()
+ )}
+ </Button>
+ </Tooltip>
+ </PopoverTrigger>
+ <PopoverContent
+ arrowClassName="fill-gray-600"
+ side="right"
+ sideOffset={12}
+ hideCloseBtn
+ className="border border-gray-600 pt-4"
+ >
+ <div className="flex flex-col space-y-4">
+ <div className="border-b border-b-gray-700 pb-2 text-sm text-mineshaft-300">
+ Configure timed access
+ </div>
+ {isExpired && <Tag colorSchema="red">Expired</Tag>}
+ <Controller
+ control={roleForm.control}
+ defaultValue="1h"
+ name={`roles.${index}.temporaryAccess.temporaryRange`}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={<TtlFormLabel label="Validity" />}
+ isError={Boolean(error?.message)}
+ errorText={error?.message}
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ <div className="flex items-center space-x-2">
+ <Button
+ size="xs"
+ onClick={() => {
+ const temporaryRange = roleForm.getValues(
+ `roles.${index}.temporaryAccess.temporaryRange`
+ );
+ if (!temporaryRange) {
+ roleForm.setError(
+ `roles.${index}.temporaryAccess.temporaryRange`,
+ { type: "required", message: "Required" },
+ { shouldFocus: true }
+ );
+ return;
+ }
+ roleForm.clearErrors(`roles.${index}.temporaryAccess.temporaryRange`);
+ roleForm.setValue(
+ `roles.${index}.temporaryAccess`,
+ {
+ isTemporary: true,
+ temporaryAccessStartTime: new Date().toISOString(),
+ temporaryRange,
+ temporaryAccessEndTime: new Date(
+ new Date().getTime() + ms(temporaryRange)
+ ).toISOString()
+ },
+ { shouldDirty: true }
+ );
+ }}
+ >
+ {temporaryAccess.isTemporary ? "Restart" : "Grant"}
+ </Button>
+ {temporaryAccess.isTemporary && (
+ <Button
+ size="xs"
+ variant="outline_bg"
+ colorSchema="danger"
+ onClick={() => {
+ roleForm.setValue(`roles.${index}.temporaryAccess`, {
+ isTemporary: false
+ });
+ }}
+ >
+ Revoke Access
+ </Button>
+ )}
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ <Tooltip content={isMemberEditDisabled ? "Access restricted" : "Remove"}>
+ <IconButton
+ variant="outline_bg"
+ className="border-none bg-mineshaft-600 py-3"
+ ariaLabel="delete-role"
+ isDisabled={isMemberEditDisabled}
+ onClick={() => {
+ if (selectedRoleList.fields.length > 1) {
+ selectedRoleList.remove(index);
+ }
+ }}
+ >
+ <FontAwesomeIcon icon={faClose} />
+ </IconButton>
+ </Tooltip>
+ </div>
+ );
+ })}
+ </div>
+ <div className="mt-4 flex justify-between space-x-2">
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Edit}
+ a={ProjectPermissionSub.Identity}
+ >
+ {(isAllowed) => (
+ <Button
+ variant="outline_bg"
+ isDisabled={!isAllowed}
+ onClick={() =>
+ selectedRoleList.append({
+ slug: ProjectMembershipRole.Member,
+ temporaryAccess: { isTemporary: false }
+ })
+ }
+ >
+ Add Role
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ <Button
+ type="submit"
+ className={twMerge(
+ "transition-all",
+ "opacity-0",
+ roleForm.formState.isDirty && "opacity-100"
+ )}
+ isLoading={roleForm.formState.isSubmitting}
+ >
+ Save Changes
+ </Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/IdentityRoleForm.tsx b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/IdentityRoleForm.tsx
new file mode 100644
index 0000000000..e354f1015d
--- /dev/null
+++ b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/IdentityRoleForm.tsx
@@ -0,0 +1,20 @@
+import { IdentityMembership } from "@app/hooks/api/identities/types";
+
+import { IdentityRbacSection } from "./IdentityRbacSection";
+import { SpecificPrivilegeSection } from "./SpecificPrivilegeSection";
+
+type Props = {
+ identityProjectMember: IdentityMembership;
+ onOpenUpgradeModal: (title: string) => void;
+};
+export const IdentityRoleForm = ({ identityProjectMember, onOpenUpgradeModal }: Props) => {
+ return (
+ <div>
+ <IdentityRbacSection
+ identityProjectMember={identityProjectMember}
+ onOpenUpgradeModal={onOpenUpgradeModal}
+ />
+ <SpecificPrivilegeSection identityId={identityProjectMember?.identity?.id} />
+ </div>
+ );
+};
diff --git a/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/SpecificPrivilegeSection.tsx b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/SpecificPrivilegeSection.tsx
new file mode 100644
index 0000000000..806072a891
--- /dev/null
+++ b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/SpecificPrivilegeSection.tsx
@@ -0,0 +1,515 @@
+import { Controller, useForm } from "react-hook-form";
+import { faCancel, faCaretDown, faClock, faClose, faSave } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { formatDistance } from "date-fns";
+import ms from "ms";
+import { twMerge } from "tailwind-merge";
+import { z } from "zod";
+
+import { TtlFormLabel } from "@app/components/features";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ Checkbox,
+ DeleteActionModal,
+ FormControl,
+ FormLabel,
+ IconButton,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Select,
+ SelectItem,
+ Spinner,
+ Tag,
+ Tooltip
+} from "@app/components/v2";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSub,
+ useProjectPermission,
+ useWorkspace
+} from "@app/context";
+import { usePopUp } from "@app/hooks";
+import {
+ TProjectUserPrivilege,
+ useCreateIdentityProjectAdditionalPrivilege,
+ useDeleteIdentityProjectAdditionalPrivilege,
+ useUpdateIdentityProjectAdditionalPrivilege
+} from "@app/hooks/api";
+import { useListIdentityProjectPrivileges } from "@app/hooks/api/identityProjectAdditionalPrivilege/queries";
+
+const secretPermissionSchema = z.object({
+ secretPath: z.string().optional(),
+ environmentSlug: z.string(),
+ [ProjectPermissionActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionActions.Read]: z.boolean().optional(),
+ [ProjectPermissionActions.Create]: z.boolean().optional(),
+ [ProjectPermissionActions.Delete]: z.boolean().optional(),
+ temporaryAccess: z.discriminatedUnion("isTemporary", [
+ z.object({
+ isTemporary: z.literal(true),
+ temporaryRange: z.string().min(1),
+ temporaryAccessStartTime: z.string().datetime(),
+ temporaryAccessEndTime: z.string().datetime().nullable().optional()
+ }),
+ z.object({
+ isTemporary: z.literal(false)
+ })
+ ])
+});
+type TSecretPermissionForm = z.infer<typeof secretPermissionSchema>;
+const SpecificPrivilegeSecretForm = ({
+ privilege,
+ identityId
+}: {
+ privilege: TProjectUserPrivilege;
+ identityId: string;
+}) => {
+ const { currentWorkspace } = useWorkspace();
+ const projectSlug = currentWorkspace?.slug || "";
+
+ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
+ "deletePrivilege"
+ ] as const);
+ const { permission } = useProjectPermission();
+ const isMemberEditDisabled = permission.cannot(
+ ProjectPermissionActions.Edit,
+ ProjectPermissionSub.Identity
+ );
+
+ const updateIdentityPrivilege = useUpdateIdentityProjectAdditionalPrivilege();
+ const deleteIdentityPrivilege = useDeleteIdentityProjectAdditionalPrivilege();
+
+ const privilegeForm = useForm<TSecretPermissionForm>({
+ resolver: zodResolver(secretPermissionSchema),
+ values: {
+ environmentSlug: privilege.permissions?.[0]?.conditions?.environment,
+ // secret path will be inside $glob operator
+ secretPath: privilege.permissions?.[0]?.conditions?.secretPath?.$glob || "",
+ read: privilege.permissions?.some(({ action }) =>
+ action.includes(ProjectPermissionActions.Read)
+ ),
+ edit: privilege.permissions?.some(({ action }) =>
+ action.includes(ProjectPermissionActions.Edit)
+ ),
+ create: privilege.permissions?.some(({ action }) =>
+ action.includes(ProjectPermissionActions.Create)
+ ),
+ delete: privilege.permissions?.some(({ action }) =>
+ action.includes(ProjectPermissionActions.Delete)
+ ),
+ // zod will pick it
+ temporaryAccess: privilege
+ }
+ });
+
+ const temporaryAccessField = privilegeForm.watch("temporaryAccess");
+ const isTemporary = temporaryAccessField?.isTemporary;
+ const isExpired =
+ temporaryAccessField.isTemporary &&
+ new Date() > new Date(temporaryAccessField.temporaryAccessEndTime || "");
+
+ const handleUpdatePrivilege = async (data: TSecretPermissionForm) => {
+ if (updateIdentityPrivilege.isLoading) return;
+ try {
+ const actions = [
+ { action: ProjectPermissionActions.Read, allowed: data.read },
+ { action: ProjectPermissionActions.Create, allowed: data.create },
+ { action: ProjectPermissionActions.Delete, allowed: data.delete },
+ { action: ProjectPermissionActions.Edit, allowed: data.edit }
+ ];
+ const conditions: Record<string, any> = { environment: data.environmentSlug };
+ if (data.secretPath) {
+ conditions.secretPath = { $glob: data.secretPath };
+ }
+ await updateIdentityPrivilege.mutateAsync({
+ data: {
+ ...data.temporaryAccess,
+ permissions: actions
+ .filter(({ allowed }) => allowed)
+ .map(({ action }) => ({
+ action,
+ subject: [ProjectPermissionSub.Secrets],
+ conditions
+ }))
+ },
+ slug: privilege.slug,
+ identityId,
+ projectSlug
+ });
+ createNotification({
+ type: "success",
+ text: "Successfully updated privilege"
+ });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: "Failed to update privilege"
+ });
+ }
+ };
+
+ const handleDeletePrivilege = async () => {
+ if (deleteIdentityPrivilege.isLoading) return;
+ try {
+ await deleteIdentityPrivilege.mutateAsync({
+ identityId,
+ slug: privilege.slug,
+ projectSlug
+ });
+ createNotification({
+ type: "success",
+ text: "Successfully deleted privilege"
+ });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: "Failed to delete privilege"
+ });
+ }
+ };
+
+ const getAccessLabel = () => {
+ if (isExpired) return "Access expired";
+ if (!temporaryAccessField?.isTemporary) return "Permanent";
+ return formatDistance(new Date(temporaryAccessField.temporaryAccessEndTime || ""), new Date());
+ };
+
+ return (
+ <div className="mt-4">
+ <form onSubmit={privilegeForm.handleSubmit(handleUpdatePrivilege)}>
+ <div className="flex items-start space-x-4">
+ <Controller
+ control={privilegeForm.control}
+ name="environmentSlug"
+ render={({ field: { onChange, ...field } }) => (
+ <FormControl label="Env">
+ <Select
+ {...field}
+ isDisabled={isMemberEditDisabled}
+ className="bg-mineshaft-600"
+ onValueChange={(e) => onChange(e)}
+ // className="w-full border border-mineshaft-500 bg-mineshaft-700 text-mineshaft-100"
+ >
+ {currentWorkspace?.environments?.map(({ slug, id }) => (
+ <SelectItem value={slug} key={id}>
+ {slug}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={privilegeForm.control}
+ name="secretPath"
+ render={({ field }) => (
+ <FormControl label="Secret Path">
+ <Input {...field} isDisabled={isMemberEditDisabled} className="w-48" />
+ </FormControl>
+ )}
+ />
+ <div className="flex flex-grow justify-between">
+ <Controller
+ control={privilegeForm.control}
+ name="read"
+ render={({ field }) => (
+ <div className="flex flex-col items-center">
+ <FormLabel label="View" className="mb-4" />
+ <Checkbox
+ isDisabled={isMemberEditDisabled}
+ id="secret-read"
+ className="h-5 w-5"
+ isChecked={field.value}
+ onCheckedChange={(isChecked) => field.onChange(isChecked)}
+ />
+ </div>
+ )}
+ />
+ <Controller
+ control={privilegeForm.control}
+ name="create"
+ render={({ field }) => (
+ <div className="flex flex-col items-center">
+ <FormLabel label="Create" className="mb-4" />
+ <Checkbox
+ isDisabled={isMemberEditDisabled}
+ id="secret-create"
+ className="h-5 w-5"
+ isChecked={field.value}
+ onCheckedChange={(isChecked) => field.onChange(isChecked)}
+ />
+ </div>
+ )}
+ />
+ <Controller
+ control={privilegeForm.control}
+ name="edit"
+ render={({ field }) => (
+ <div className="flex flex-col items-center">
+ <FormLabel label="Modify" className="mb-4" />
+ <Checkbox
+ isDisabled={isMemberEditDisabled}
+ id="secret-modify"
+ className="h-5 w-5"
+ isChecked={field.value}
+ onCheckedChange={(isChecked) => field.onChange(isChecked)}
+ />
+ </div>
+ )}
+ />
+ <Controller
+ control={privilegeForm.control}
+ name="delete"
+ render={({ field }) => (
+ <div className="flex flex-col items-center">
+ <FormLabel label="Delete" className="mb-4" />
+ <Checkbox
+ isDisabled={isMemberEditDisabled}
+ id="secret-delete"
+ className="h-5 w-5"
+ isChecked={field.value}
+ onCheckedChange={(isChecked) => field.onChange(isChecked)}
+ />
+ </div>
+ )}
+ />
+ </div>
+ <div className="mt-7 flex items-center space-x-2">
+ <Popover>
+ <PopoverTrigger disabled={isMemberEditDisabled}>
+ <Tooltip
+ asChild
+ content={isExpired ? "Timed access expired" : "Grant timed access"}
+ >
+ <Button
+ variant="outline_bg"
+ isDisabled={isMemberEditDisabled}
+ leftIcon={isTemporary ? <FontAwesomeIcon icon={faClock} /> : undefined}
+ rightIcon={<FontAwesomeIcon icon={faCaretDown} className="ml-2" />}
+ className={twMerge(
+ "border-none py-1.5 capitalize",
+ isTemporary && "text-primary",
+ isExpired && "text-red-600"
+ )}
+ >
+ {getAccessLabel()}
+ </Button>
+ </Tooltip>
+ </PopoverTrigger>
+ <PopoverContent
+ arrowClassName="fill-gray-600"
+ side="right"
+ sideOffset={12}
+ hideCloseBtn
+ className="border border-gray-600 pt-4"
+ >
+ <div className="flex flex-col space-y-4">
+ <div className="border-b border-b-gray-700 pb-2 text-sm text-mineshaft-300">
+ Configure timed access
+ </div>
+ {isExpired && <Tag colorSchema="red">Expired</Tag>}
+ <Controller
+ control={privilegeForm.control}
+ defaultValue="1h"
+ name="temporaryAccess.temporaryRange"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={<TtlFormLabel label="Validity" />}
+ isError={Boolean(error?.message)}
+ errorText={error?.message}
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ <div className="flex items-center space-x-2">
+ <Button
+ size="xs"
+ onClick={() => {
+ const temporaryRange = privilegeForm.getValues(
+ "temporaryAccess.temporaryRange"
+ );
+ if (!temporaryRange) {
+ privilegeForm.setError(
+ "temporaryAccess.temporaryRange",
+ { type: "required", message: "Required" },
+ { shouldFocus: true }
+ );
+ return;
+ }
+ privilegeForm.clearErrors("temporaryAccess.temporaryRange");
+ privilegeForm.setValue(
+ "temporaryAccess",
+ {
+ isTemporary: true,
+ temporaryAccessStartTime: new Date().toISOString(),
+ temporaryRange,
+ temporaryAccessEndTime: new Date(
+ new Date().getTime() + ms(temporaryRange)
+ ).toISOString()
+ },
+ { shouldDirty: true }
+ );
+ }}
+ >
+ {temporaryAccessField.isTemporary ? "Restart" : "Grant"}
+ </Button>
+ {temporaryAccessField.isTemporary && (
+ <Button
+ size="xs"
+ variant="outline_bg"
+ colorSchema="danger"
+ onClick={() => {
+ privilegeForm.setValue("temporaryAccess", {
+ isTemporary: false
+ });
+ }}
+ >
+ Revoke Access
+ </Button>
+ )}
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ {privilegeForm.formState.isDirty ? (
+ <>
+ <Tooltip content={isMemberEditDisabled ? "Access restricted" : "Save"}>
+ <IconButton
+ isDisabled={isMemberEditDisabled}
+ className="border-none py-2.5"
+ ariaLabel="save-privilege"
+ type="submit"
+ >
+ {privilegeForm.formState.isSubmitting ? (
+ <Spinner size="xs" className="m-0 h-3 w-3 text-slate-500" />
+ ) : (
+ <FontAwesomeIcon icon={faSave} />
+ )}
+ </IconButton>
+ </Tooltip>
+ <Tooltip content="Cancel">
+ <IconButton
+ variant="outline_bg"
+ className="border-none bg-mineshaft-600 py-2.5"
+ ariaLabel="delete-privilege"
+ isDisabled={privilegeForm.formState.isSubmitting}
+ onClick={() => privilegeForm.reset()}
+ >
+ <FontAwesomeIcon icon={faCancel} />
+ </IconButton>
+ </Tooltip>
+ </>
+ ) : (
+ <Tooltip content={isMemberEditDisabled ? "Access restricted" : "Delete"}>
+ <IconButton
+ isDisabled={isMemberEditDisabled}
+ variant="outline_bg"
+ className="border-none bg-mineshaft-600 py-2.5"
+ ariaLabel="delete-privilege"
+ onClick={() => handlePopUpOpen("deletePrivilege")}
+ >
+ <FontAwesomeIcon icon={faClose} />
+ </IconButton>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ </form>
+ <DeleteActionModal
+ isOpen={popUp.deletePrivilege.isOpen}
+ title="Remove user additional privilege"
+ onChange={(isOpen) => handlePopUpToggle("deletePrivilege", isOpen)}
+ deleteKey="delete"
+ onClose={() => handlePopUpClose("deletePrivilege")}
+ onDeleteApproved={handleDeletePrivilege}
+ />
+ </div>
+ );
+};
+
+type Props = {
+ identityId: string;
+};
+
+export const SpecificPrivilegeSection = ({ identityId }: Props) => {
+ const { currentWorkspace } = useWorkspace();
+ const projectSlug = currentWorkspace?.slug || "";
+ const { data: identityPrivileges, isLoading } = useListIdentityProjectPrivileges({
+ identityId,
+ projectSlug
+ });
+
+ const createIdentityPrivilege = useCreateIdentityProjectAdditionalPrivilege();
+
+ const handleCreatePrivilege = async () => {
+ if (createIdentityPrivilege.isLoading) return;
+ try {
+ await createIdentityPrivilege.mutateAsync({
+ permissions: [
+ {
+ action: ProjectPermissionActions.Read,
+ subject: [ProjectPermissionSub.Secrets],
+ conditions: {
+ environment: currentWorkspace?.environments?.[0].slug
+ }
+ }
+ ],
+ identityId,
+ projectSlug
+ });
+ createNotification({
+ type: "success",
+ text: "Successfully created privilege"
+ });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: "Failed to create privilege"
+ });
+ }
+ };
+
+ return (
+ <div className="mt-6 border-t border-t-gray-700 pt-6">
+ <div className="flex items-center space-x-2 text-lg font-medium">
+ Additional Privileges
+ {isLoading && <Spinner size="xs" />}
+ </div>
+ <p className="text-sm text-mineshaft-400">
+ Select individual privileges to associate with the identity.
+ </p>
+ <div>
+ {identityPrivileges
+ ?.filter(({ permissions }) =>
+ permissions?.[0]?.subject?.includes(ProjectPermissionSub.Secrets)
+ )
+ ?.map((privilege) => (
+ <SpecificPrivilegeSecretForm
+ privilege={privilege as TProjectUserPrivilege}
+ identityId={identityId}
+ key={privilege?.id}
+ />
+ ))}
+ </div>
+ <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Identity}>
+ {(isAllowed) => (
+ <Button
+ variant="outline_bg"
+ className="mt-4"
+ onClick={handleCreatePrivilege}
+ isLoading={createIdentityPrivilege.isLoading}
+ isDisabled={!isAllowed}
+ >
+ Add additional privilege
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </div>
+ );
+};
diff --git a/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/index.tsx b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/index.tsx
new file mode 100644
index 0000000000..f59675cb3d
--- /dev/null
+++ b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoleForm/index.tsx
@@ -0,0 +1 @@
+export { IdentityRoleForm } from "./IdentityRoleForm";
diff --git a/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoles.tsx b/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoles.tsx
deleted file mode 100644
index 6ff10cfa83..0000000000
--- a/frontend/src/views/Project/MembersPage/components/IdentityTab/components/IdentityRoles.tsx
+++ /dev/null
@@ -1,459 +0,0 @@
-import { useState } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { faCheck, faClock, faEdit, faSearch } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { twMerge } from "tailwind-merge";
-import { z } from "zod";
-
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- Checkbox,
- FormControl,
- HoverCard,
- HoverCardContent,
- HoverCardTrigger,
- IconButton,
- Input,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Spinner,
- Tag,
- Tooltip
-} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
-import { usePopUp } from "@app/hooks";
-import { useGetProjectRoles, useUpdateIdentityWorkspaceRole } from "@app/hooks/api";
-import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { TWorkspaceUser } from "@app/hooks/api/types";
-import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/workspace/types";
-import { groupBy } from "@app/lib/fn/array";
-
-const temporaryRoleFormSchema = z.object({
- temporaryRange: z.string().min(1, "Required")
-});
-
-type TTemporaryRoleFormSchema = z.infer<typeof temporaryRoleFormSchema>;
-
-type TTemporaryRoleFormProps = {
- temporaryConfig?: {
- isTemporary?: boolean;
- temporaryAccessEndTime?: string | null;
- temporaryAccessStartTime?: string | null;
- temporaryRange?: string | null;
- };
- onSetTemporary: (data: { temporaryRange: string; temporaryAccessStartTime?: string }) => void;
- onRemoveTemporary: () => void;
-};
-
-const IdentityTemporaryRoleForm = ({
- temporaryConfig: defaultValues = {},
- onSetTemporary,
- onRemoveTemporary
-}: TTemporaryRoleFormProps) => {
- const { popUp, handlePopUpToggle } = usePopUp(["setTempRole"] as const);
- const { control, handleSubmit } = useForm<TTemporaryRoleFormSchema>({
- resolver: zodResolver(temporaryRoleFormSchema),
- values: {
- temporaryRange: defaultValues.temporaryRange || "1h"
- }
- });
- const isTemporaryFieldValue = defaultValues.isTemporary;
- const isExpired =
- isTemporaryFieldValue && new Date() > new Date(defaultValues.temporaryAccessEndTime || "");
-
- return (
- <Popover
- open={popUp.setTempRole.isOpen}
- onOpenChange={(isOpen) => {
- handlePopUpToggle("setTempRole", isOpen);
- }}
- >
- <PopoverTrigger>
- <IconButton ariaLabel="role-temp" variant="plain" size="md">
- <Tooltip content={isExpired ? "Access Expired" : "Grant Temporary Access"}>
- <FontAwesomeIcon
- icon={faClock}
- className={twMerge(
- isTemporaryFieldValue && "text-primary",
- isExpired && "text-red-600"
- )}
- />
- </Tooltip>
- </IconButton>
- </PopoverTrigger>
- <PopoverContent
- arrowClassName="fill-gray-600"
- side="right"
- sideOffset={12}
- hideCloseBtn
- className="border border-gray-600 pt-4"
- >
- <div className="flex flex-col space-y-4">
- <div className="border-b border-b-gray-700 pb-2 text-sm text-mineshaft-300">
- Set Role Temporarily
- </div>
- {isExpired && <Tag colorSchema="red">Expired</Tag>}
- <Controller
- control={control}
- name="temporaryRange"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Validity"
- isError={Boolean(error?.message)}
- errorText={error?.message}
- helperText={
- <span>
- 1m, 2h, 3d.{" "}
- <a
- href="https://github.com/vercel/ms?tab=readme-ov-file#examples"
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary-700"
- >
- More
- </a>
- </span>
- }
- >
- <Input {...field} />
- </FormControl>
- )}
- />
- <div className="flex items-center space-x-2">
- {isTemporaryFieldValue && (
- <Button
- size="xs"
- type="submit"
- onClick={() => {
- handleSubmit(({ temporaryRange }) => {
- onSetTemporary({
- temporaryRange,
- temporaryAccessStartTime: new Date().toISOString()
- });
- handlePopUpToggle("setTempRole");
- })();
- }}
- >
- Restart
- </Button>
- )}
- {!isTemporaryFieldValue ? (
- <Button
- size="xs"
- type="submit"
- onClick={() =>
- handleSubmit(({ temporaryRange }) => {
- onSetTemporary({
- temporaryRange,
- temporaryAccessStartTime:
- defaultValues.temporaryAccessStartTime || new Date().toISOString()
- });
- handlePopUpToggle("setTempRole");
- })()
- }
- >
- Grant access
- </Button>
- ) : (
- <Button
- size="xs"
- variant="outline_bg"
- colorSchema="danger"
- onClick={() => {
- onRemoveTemporary();
- handlePopUpToggle("setTempRole");
- }}
- >
- Revoke Access
- </Button>
- )}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- );
-};
-
-const formSchema = z.record(
- z.object({
- isChecked: z.boolean().optional(),
- temporaryAccess: z.union([
- z.object({
- isTemporary: z.literal(true),
- temporaryRange: z.string().min(1),
- temporaryAccessStartTime: z.string().datetime(),
- temporaryAccessEndTime: z.string().datetime().nullable().optional()
- }),
- z.boolean()
- ])
- })
-);
-type TForm = z.infer<typeof formSchema>;
-
-export type TMemberRolesProp = {
- disableEdit?: boolean;
- identityId: string;
- roles: TWorkspaceUser["roles"];
-};
-
-const MAX_ROLES_TO_BE_SHOWN_IN_TABLE = 2;
-
-export const IdentityRoles = ({
- roles = [],
- disableEdit = false,
- identityId
-}: TMemberRolesProp) => {
- const { currentWorkspace } = useWorkspace();
-
- const { popUp, handlePopUpToggle } = usePopUp(["editRole"] as const);
- const [searchRoles, setSearchRoles] = useState("");
-
- const {
- handleSubmit,
- control,
- reset,
- setValue,
- formState: { isSubmitting, isDirty }
- } = useForm<TForm>({
- resolver: zodResolver(formSchema)
- });
-
- const workspaceId = currentWorkspace?.id || "";
-
- const { data: projectRoles, isLoading: isRolesLoading } = useGetProjectRoles(workspaceId);
- const userRolesGroupBySlug = groupBy(roles, ({ customRoleSlug, role }) => customRoleSlug || role);
-
- const updateIdentityWorkspaceRole = useUpdateIdentityWorkspaceRole();
-
- const handleRoleUpdate = async (data: TForm) => {
- const selectedRoles = Object.keys(data)
- .filter((el) => Boolean(data[el].isChecked))
- .map((el) => {
- const isTemporary = Boolean(data[el].temporaryAccess);
- if (!isTemporary) {
- return { role: el, isTemporary: false as const };
- }
-
- const tempCfg = data[el].temporaryAccess as {
- temporaryRange: string;
- temporaryAccessStartTime: string;
- };
-
- return {
- role: el,
- isTemporary: true as const,
- temporaryMode: ProjectUserMembershipTemporaryMode.Relative,
- temporaryRange: tempCfg.temporaryRange,
- temporaryAccessStartTime: tempCfg.temporaryAccessStartTime
- };
- });
-
- try {
- await updateIdentityWorkspaceRole.mutateAsync({
- workspaceId,
- identityId,
- roles: selectedRoles
- });
- createNotification({ text: "Successfully updated identity role", type: "success" });
- handlePopUpToggle("editRole");
- setSearchRoles("");
- } catch (err) {
- createNotification({ text: "Failed to update identity role", type: "error" });
- }
- };
-
- const formatRoleName = (role: string, customRoleName?: string) => {
- if (role === ProjectMembershipRole.Custom) return customRoleName;
- if (role === ProjectMembershipRole.Member) return "Developer";
- return role;
- };
-
- return (
- <div className="flex items-center space-x-2">
- {roles
- .slice(0, MAX_ROLES_TO_BE_SHOWN_IN_TABLE)
- .map(({ role, customRoleName, id, isTemporary, temporaryAccessEndTime }) => {
- const isExpired = new Date() > new Date(temporaryAccessEndTime || ("" as string));
- return (
- <Tag key={id} className="capitalize">
- <div className="flex items-center space-x-2">
- <div>{formatRoleName(role, customRoleName)}</div>
- {isTemporary && (
- <div>
- <Tooltip content={isExpired ? "Expired Temporary Access" : "Temporary Access"}>
- <FontAwesomeIcon
- icon={faClock}
- className={twMerge(isExpired && "text-red-600")}
- />
- </Tooltip>
- </div>
- )}
- </div>
- </Tag>
- );
- })}
- {roles.length > MAX_ROLES_TO_BE_SHOWN_IN_TABLE && (
- <HoverCard>
- <HoverCardTrigger>
- <Tag>+{roles.length - MAX_ROLES_TO_BE_SHOWN_IN_TABLE}</Tag>
- </HoverCardTrigger>
- <HoverCardContent className="border border-gray-700 bg-mineshaft-800 p-4">
- {roles
- .slice(MAX_ROLES_TO_BE_SHOWN_IN_TABLE)
- .map(({ role, customRoleName, id, isTemporary, temporaryAccessEndTime }) => {
- const isExpired = new Date() > new Date(temporaryAccessEndTime || ("" as string));
- return (
- <Tag key={id} className="capitalize">
- <div className="flex items-center space-x-2">
- <div>{formatRoleName(role, customRoleName)}</div>
- {isTemporary && (
- <div>
- <Tooltip
- content={isExpired ? "Expired Temporary Access" : "Temporary Access"}
- >
- <FontAwesomeIcon
- icon={faClock}
- className={twMerge(
- new Date() > new Date(temporaryAccessEndTime as string) &&
- "text-red-600"
- )}
- />
- </Tooltip>
- </div>
- )}
- </div>
- </Tag>
- );
- })}{" "}
- </HoverCardContent>
- </HoverCard>
- )}
- <div>
- <Popover
- open={popUp.editRole.isOpen}
- onOpenChange={(isOpen) => {
- handlePopUpToggle("editRole", isOpen);
- reset();
- }}
- >
- {!disableEdit && (
- <PopoverTrigger>
- <IconButton size="sm" variant="plain" ariaLabel="update">
- <FontAwesomeIcon icon={faEdit} />
- </IconButton>
- </PopoverTrigger>
- )}
- <PopoverContent hideCloseBtn className="pt-4">
- {isRolesLoading ? (
- <div className="flex h-8 w-full items-center justify-center">
- <Spinner />
- </div>
- ) : (
- <form onSubmit={handleSubmit(handleRoleUpdate)} id="role-update-form">
- <div className="thin-scrollbar max-h-80 space-y-4 overflow-y-auto">
- {projectRoles
- ?.filter(
- ({ name, slug }) =>
- name.toLowerCase().includes(searchRoles.toLowerCase()) ||
- slug.toLowerCase().includes(searchRoles.toLowerCase())
- )
- ?.map(({ id, name, slug }) => {
- const userProjectRoleDetails = userRolesGroupBySlug?.[slug]?.[0];
-
- return (
- <div key={id} className="flex items-center space-x-4">
- <div className="flex-grow">
- <Controller
- control={control}
- defaultValue={Boolean(userProjectRoleDetails?.id)}
- name={`${slug}.isChecked`}
- render={({ field }) => (
- <Checkbox
- id={slug}
- isChecked={field.value}
- onCheckedChange={(isChecked) => {
- field.onChange(isChecked);
- setValue(`${slug}.temporaryAccess`, false);
- }}
- >
- {name}
- </Checkbox>
- )}
- />
- </div>
- <div>
- <Controller
- control={control}
- name={`${slug}.temporaryAccess`}
- defaultValue={
- userProjectRoleDetails?.isTemporary
- ? {
- isTemporary: true,
- temporaryAccessStartTime:
- userProjectRoleDetails.temporaryAccessStartTime as string,
- temporaryRange:
- userProjectRoleDetails.temporaryRange as string,
- temporaryAccessEndTime:
- userProjectRoleDetails.temporaryAccessEndTime
- }
- : false
- }
- render={({ field }) => (
- <IdentityTemporaryRoleForm
- temporaryConfig={
- typeof field.value === "boolean"
- ? { isTemporary: field.value }
- : field.value
- }
- onSetTemporary={(data) => {
- setValue(`${slug}.isChecked`, true, { shouldDirty: true });
- console.log(data);
- field.onChange({ isTemporary: true, ...data });
- }}
- onRemoveTemporary={() => {
- setValue(`${slug}.isChecked`, false, { shouldDirty: true });
- field.onChange(false);
- }}
- />
- )}
- />
- </div>
- </div>
- );
- })}
- </div>
- <div className="mt-3 flex items-center space-x-2 border-t border-t-gray-700 pt-3">
- <div>
- <Input
- className="w-full p-1.5 pl-8"
- size="xs"
- value={searchRoles}
- onChange={(el) => setSearchRoles(el.target.value)}
- leftIcon={<FontAwesomeIcon icon={faSearch} />}
- placeholder="Search roles.."
- />
- </div>
- <div>
- <Button
- size="xs"
- type="submit"
- form="role-update-form"
- leftIcon={<FontAwesomeIcon icon={faCheck} />}
- isDisabled={!isDirty || isSubmitting}
- isLoading={isSubmitting}
- >
- Save
- </Button>
- </div>
- </div>
- </form>
- )}
- </PopoverContent>
- </Popover>
- </div>
- </div>
- );
-};
diff --git a/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberListTab.tsx b/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberListTab.tsx
index 9f1711199c..3bb29ff613 100644
--- a/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberListTab.tsx
+++ b/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberListTab.tsx
@@ -210,7 +210,7 @@ export const MemberListTab = () => {
return (
<motion.div
- key="panel-1"
+ key="user-role-1"
className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"
transition={{ duration: 0.15 }}
initial={{ opacity: 0, translateX: 30 }}
diff --git a/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberRoleForm/SpecificPrivilegeSection.tsx b/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberRoleForm/SpecificPrivilegeSection.tsx
index 8aaf221429..6304322b02 100644
--- a/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberRoleForm/SpecificPrivilegeSection.tsx
+++ b/frontend/src/views/Project/MembersPage/components/MemberListTab/MemberRoleForm/SpecificPrivilegeSection.tsx
@@ -375,7 +375,7 @@ const SpecificPrivilegeSecretForm = ({ privilege }: { privilege: TProjectUserPri
type="submit"
>
{privilegeForm.formState.isSubmitting ? (
- <Spinner size="sm" />
+ <Spinner size="xs" className="m-0 text-slate-500 w-3 h-3" />
) : (
<FontAwesomeIcon icon={faSave} />
)}
@@ -460,7 +460,7 @@ export const SpecificPrivilegeSection = ({ membershipId }: Props) => {
return (
<div className="mt-6 border-t border-t-gray-700 pt-6">
- <div className="text-lg font-medium flex items-center space-x-2">
+ <div className="flex items-center space-x-2 text-lg font-medium">
Additional Privileges
{isLoading && <Spinner size="xs" />}
</div>