Skip to content

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

refactor(ui): share role-assignment logic between the two editors

lobocv0f56b5e4d981
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberMultiRoleModify.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberMultiRoleModify.tsx
index 47646af6c8..895cd7867d 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberMultiRoleModify.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberMultiRoleModify.tsx
@@ -1,86 +1,27 @@
-/* eslint-disable no-nested-ternary */
-import { useMemo } from "react";
-import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { useFieldArray, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
-import { format, formatDistance } from "date-fns";
-import { ChevronDownIcon, ClockIcon, PlusIcon, TrashIcon } from "lucide-react";
-import ms from "ms";
-import picomatch from "picomatch";
-import { twMerge } from "tailwind-merge";
+import { PlusIcon, TrashIcon } from "lucide-react";
import { z } from "zod";
-import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
-import {
- Badge,
- Button,
- Field,
- FieldError,
- FieldLabel,
- IconButton,
- Input,
- PageLoader,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
+import { Button, IconButton, PageLoader } from "@app/components/v3";
import {
ProjectPermissionActions,
- ProjectPermissionMemberActions,
ProjectPermissionSub,
useProject,
- useProjectPermission,
useSubscription
} from "@app/context";
-import { formatProjectRoleName } from "@app/helpers/roles";
-import { useGetProjectRoles, useUpdateUserWorkspaceRole } from "@app/hooks/api";
-import { ProjectType, ProjectUserMembershipTemporaryMode } from "@app/hooks/api/projects/types";
+import { useUpdateUserWorkspaceRole } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { TWorkspaceUser } from "@app/hooks/api/types";
-import {
- canModifyByGrantConditions,
- filterByGrantConditions,
- getMemberAssignRoleConditions
-} from "@app/lib/fn/permission";
-const TEMPORARY_RANGE_ERROR = "Only valid time values are accepted (1h, 20m, 2d).";
+import { formRoleToPayload, roleAssignmentSchema, toFormAssignment } from "./roleAssignment";
+import { RoleAssignmentRow } from "./RoleAssignmentRow";
+import { useMemberRoleGrant } from "./useMemberRoleGrant";
-const isValidTemporaryRange = (value?: string) => {
- if (!value?.trim()) return false;
- const parsedMs = ms(value);
- return typeof parsedMs === "number" && Number.isFinite(parsedMs) && parsedMs > 0;
-};
-
-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, "Required")
- .refine(isValidTemporaryRange, TEMPORARY_RANGE_ERROR),
- temporaryAccessStartTime: z.string().datetime(),
- temporaryAccessEndTime: z.string().datetime().nullable().optional()
- }),
- z.object({
- isTemporary: z.literal(false)
- })
- ])
- })
- .array()
-});
+const roleFormSchema = z.object({ roles: roleAssignmentSchema.array() });
type TRoleForm = z.infer<typeof roleFormSchema>;
type Props = {
@@ -92,106 +33,20 @@ type Props = {
export const MemberMultiRoleModify = ({ projectMember, onOpenUpgradeModal, onSuccess }: Props) => {
const { subscription } = useSubscription();
const { projectId, currentProject } = useProject();
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
- projectId,
- currentProject?.type
- );
- const { permission } = useProjectPermission();
- const isMemberEditDisabled = permission.cannot(
- ProjectPermissionMemberActions.Edit,
- ProjectPermissionSub.Member
- );
-
- const assignRoleConditions = useMemo(
- () => getMemberAssignRoleConditions(permission),
- [permission]
- );
-
- const canModifyMemberRoles = useMemo(() => {
- const memberEmail = projectMember?.user?.email;
- if (!memberEmail) return false;
-
- return canModifyByGrantConditions({
- targetValue: memberEmail,
- allowed: assignRoleConditions?.emails,
- forbidden: assignRoleConditions?.forbiddenEmails,
- isMatch: (value, pattern) => picomatch.isMatch(value, pattern)
- });
- }, [assignRoleConditions, projectMember?.user?.email]);
-
- const filteredRoles = useMemo(
- () =>
- filterByGrantConditions(projectRoles ?? [], {
- getKey: (role) => role.slug,
- allowed: assignRoleConditions?.roles,
- forbidden: assignRoleConditions?.forbiddenRoles
- }),
- [projectRoles, assignRoleConditions]
- );
-
- const assignableRoleSlugs = useMemo(
- () => new Set(filteredRoles.map((r) => r.slug)),
- [filteredRoles]
- );
-
- const getRolesForSelect = (currentSlug: string) => {
- const assignable = filteredRoles;
- const currentInAssignable = assignableRoleSlugs.has(currentSlug);
- if (currentInAssignable) return assignable;
-
- const currentRole = projectRoles?.find((r) => r.slug === currentSlug) ?? {
- slug: currentSlug,
- name: formatProjectRoleName(currentSlug),
- id: currentSlug
- };
- return [currentRole, ...assignable];
- };
-
- const isEditDisabled = isMemberEditDisabled || !canModifyMemberRoles;
+ const { isRolesLoading, assignableRoleSlugs, getRolesForSelect, isEditDisabled } =
+ useMemberRoleGrant(projectMember);
+ const updateMembershipRole = useUpdateUserWorkspaceRole();
const roleForm = useForm<TRoleForm>({
resolver: zodResolver(roleFormSchema),
- values: {
- roles: projectMember?.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
- }
- }))
- }
+ values: { roles: projectMember?.roles?.map(toFormAssignment) ?? [] }
});
- const selectedRoleList = useFieldArray({
- name: "roles",
- control: roleForm.control
- });
-
- const formRoleField = roleForm.watch("roles");
- const updateMembershipRole = useUpdateUserWorkspaceRole();
+ const selectedRoleList = useFieldArray({ name: "roles", control: roleForm.control });
const handleRoleUpdate = async (data: TRoleForm) => {
if (updateMembershipRole.isPending) 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 sanitizedRoles = data.roles.map(formRoleToPayload);
const hasCustomRoleSelected = sanitizedRoles.some(
(el) => !Object.values(ProjectMembershipRole).includes(el.role as ProjectMembershipRole)
);
@@ -223,220 +78,17 @@ export const MemberMultiRoleModify = ({ projectMember, onOpenUpgradeModal, onSuc
return (
<form onSubmit={roleForm.handleSubmit(handleRoleUpdate)}>
<div className="flex flex-col gap-3">
- {selectedRoleList.fields.map(({ id }, index) => {
- const { temporaryAccess } = formRoleField[index];
- const isTemporary = temporaryAccess?.isTemporary;
- const isExpired =
- temporaryAccess.isTemporary &&
- new Date() > new Date(temporaryAccess.temporaryAccessEndTime || "");
-
- let durationVariant: "outline" | "warning" | "danger" = "outline";
- let text = "Permanent";
- let toolTipText = "Non-Expiring Access";
-
- if (isTemporary) {
- if (isExpired) {
- durationVariant = "danger";
- text = "Access Expired";
- toolTipText = "Timed Access Expired";
- } else {
- durationVariant = "warning";
- text = formatDistance(
- new Date(temporaryAccess.temporaryAccessEndTime || ""),
- new Date()
- );
- toolTipText = `Until ${format(
- new Date(temporaryAccess.temporaryAccessEndTime || ""),
- "yyyy-MM-dd HH:mm:ss"
- )}`;
- }
- }
-
- return (
- <div key={id} className="flex items-end gap-2">
- <Controller
- control={roleForm.control}
- name={`roles.${index}.slug`}
- render={({ field }) => {
- const rolesForSelect = getRolesForSelect(field.value);
- return (
- <Field className="min-w-0 flex-1">
- {index === 0 && <FieldLabel>Role</FieldLabel>}
- <Select
- value={field.value}
- onValueChange={field.onChange}
- disabled={isEditDisabled}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper" className="z-[70]">
- {rolesForSelect.map(({ name, slug, id: projectRoleId }) => {
- const isAssignable = assignableRoleSlugs.has(slug);
- return (
- <SelectItem
- value={slug}
- key={projectRoleId}
- disabled={!isAssignable}
- description={
- isAssignable
- ? undefined
- : "You don't have permission to assign this role"
- }
- >
- {name}
- </SelectItem>
- );
- })}
- </SelectContent>
- </Select>
- </Field>
- );
- }}
- />
- <Field className="w-44 shrink-0">
- {index === 0 && <FieldLabel>Duration</FieldLabel>}
- <Popover>
- <Tooltip>
- <TooltipTrigger asChild>
- <PopoverTrigger asChild>
- <Button
- type="button"
- variant={durationVariant}
- isDisabled={isEditDisabled}
- className="w-full capitalize"
- >
- {isTemporary && <ClockIcon />}
- {text}
- <ChevronDownIcon />
- </Button>
- </PopoverTrigger>
- </TooltipTrigger>
- <TooltipContent>{toolTipText}</TooltipContent>
- </Tooltip>
- <PopoverContent
- side="right"
- className="z-[70]"
- onWheel={(e) => e.stopPropagation()}
- onOpenAutoFocus={(e) => e.preventDefault()}
- >
- <div className="flex flex-col space-y-4">
- <div className="border-b border-b-border pb-2 text-sm text-muted">
- Configure Timed Access
- </div>
- {isExpired && <Badge variant="danger">Expired</Badge>}
- <Controller
- control={roleForm.control}
- defaultValue="1h"
- name={`roles.${index}.temporaryAccess.temporaryRange`}
- render={({ field, fieldState: { error } }) => {
- const showInvalidError =
- Boolean(field.value) && !isValidTemporaryRange(field.value);
- const errorMessage = showInvalidError
- ? TEMPORARY_RANGE_ERROR
- : error?.message;
- const canGrant = isValidTemporaryRange(field.value);
-
- return (
- <>
- <Field>
- <FieldLabel>
- <TtlFormLabel label="Validity" />
- </FieldLabel>
- <Input
- {...field}
- value={field.value ?? ""}
- isError={Boolean(errorMessage)}
- onChange={(e) => {
- field.onChange(e);
- const nextValue = e.target.value;
- if (!nextValue) {
- roleForm.setError(
- `roles.${index}.temporaryAccess.temporaryRange`,
- { type: "required", message: "Required" },
- { shouldFocus: false }
- );
- return;
- }
- if (!isValidTemporaryRange(nextValue)) {
- roleForm.setError(
- `roles.${index}.temporaryAccess.temporaryRange`,
- {
- type: "validate",
- message: TEMPORARY_RANGE_ERROR
- },
- { shouldFocus: false }
- );
- return;
- }
- roleForm.clearErrors(
- `roles.${index}.temporaryAccess.temporaryRange`
- );
- }}
- />
- {errorMessage && <FieldError>{errorMessage}</FieldError>}
- </Field>
- <div className="flex items-center space-x-2">
- <Button
- size="xs"
- variant="outline"
- isDisabled={!canGrant}
- onClick={() => {
- const temporaryRange = field.value;
- if (!isValidTemporaryRange(temporaryRange)) {
- roleForm.setError(
- `roles.${index}.temporaryAccess.temporaryRange`,
- {
- type: "validate",
- message: TEMPORARY_RANGE_ERROR
- },
- { 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 }
- );
- }}
- >
- {isTemporary ? "Restart" : "Grant"}
- </Button>
- {isTemporary && (
- <Button
- size="xs"
- variant="danger"
- onClick={() => {
- roleForm.setValue(
- `roles.${index}.temporaryAccess`,
- { isTemporary: false },
- { shouldDirty: true }
- );
- }}
- >
- Revoke Access
- </Button>
- )}
- </div>
- </>
- );
- }}
- />
- </div>
- </PopoverContent>
- </Popover>
- </Field>
+ {selectedRoleList.fields.map(({ id }, index) => (
+ <RoleAssignmentRow
+ key={id}
+ control={roleForm.control}
+ setValue={roleForm.setValue}
+ namePrefix={`roles.${index}.`}
+ showLabels={index === 0}
+ isEditDisabled={isEditDisabled}
+ assignableRoleSlugs={assignableRoleSlugs}
+ getRolesForSelect={getRolesForSelect}
+ action={
<IconButton
size="md"
variant="outline"
@@ -451,9 +103,9 @@ export const MemberMultiRoleModify = ({ projectMember, onOpenUpgradeModal, onSuc
>
<TrashIcon />
</IconButton>
- </div>
- );
- })}
+ }
+ />
+ ))}
</div>
<div className="mt-4 flex items-center justify-between gap-2">
<ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Member}>
@@ -477,11 +129,6 @@ export const MemberMultiRoleModify = ({ projectMember, onOpenUpgradeModal, onSuc
<Button
type="submit"
variant="project"
- className={twMerge(
- "transition-all",
- "cursor-default opacity-0",
- roleForm.formState.isDirty && "cursor-pointer opacity-100"
- )}
isDisabled={!roleForm.formState.isDirty || isEditDisabled}
isPending={roleForm.formState.isSubmitting}
>
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberSingleRoleModify.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberSingleRoleModify.tsx
index b42c42c970..93ef6da66f 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberSingleRoleModify.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberSingleRoleModify.tsx
@@ -1,81 +1,24 @@
-import { useMemo } from "react";
-import { Controller, useForm } from "react-hook-form";
+import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
-import { format, formatDistance } from "date-fns";
-import { ChevronDownIcon, ClockIcon } from "lucide-react";
-import ms from "ms";
-import picomatch from "picomatch";
-import { twMerge } from "tailwind-merge";
-import { z } from "zod";
-import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
-import {
- Badge,
- Button,
- Field,
- FieldError,
- FieldLabel,
- Input,
- PageLoader,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import {
- ProjectPermissionMemberActions,
- ProjectPermissionSub,
- useProject,
- useProjectPermission,
- useSubscription
-} from "@app/context";
-import { formatProjectRoleName } from "@app/helpers/roles";
-import { useGetProjectRoles, useUpdateUserWorkspaceRole } from "@app/hooks/api";
-import { ProjectType, ProjectUserMembershipTemporaryMode } from "@app/hooks/api/projects/types";
+import { Button, PageLoader } from "@app/components/v3";
+import { useProject, useSubscription } from "@app/context";
+import { useUpdateUserWorkspaceRole } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { TWorkspaceUser } from "@app/hooks/api/types";
-import {
- canModifyByGrantConditions,
- filterByGrantConditions,
- getMemberAssignRoleConditions
-} from "@app/lib/fn/permission";
-
-const TEMPORARY_RANGE_ERROR = "Only valid time values are accepted (1h, 20m, 2d).";
-
-const isValidTemporaryRange = (value?: string) => {
- if (!value?.trim()) return false;
- const parsedMs = ms(value);
- return typeof parsedMs === "number" && Number.isFinite(parsedMs) && parsedMs > 0;
-};
-
-const roleFormSchema = z.object({
- slug: z.string().min(1),
- temporaryAccess: z.discriminatedUnion("isTemporary", [
- z.object({
- isTemporary: z.literal(true),
- temporaryRange: z
- .string()
- .min(1, "Required")
- .refine(isValidTemporaryRange, TEMPORARY_RANGE_ERROR),
- temporaryAccessStartTime: z.string().datetime(),
- temporaryAccessEndTime: z.string().datetime().nullable().optional()
- }),
- z.object({
- isTemporary: z.literal(false)
- })
- ])
-});
-type TRoleForm = z.infer<typeof roleFormSchema>;
-export type MemberRoleAssignment = TWorkspaceUser["roles"][number];
+import {
+ existingRoleToPayload,
+ formRoleToPayload,
+ MemberRoleAssignment,
+ roleAssignmentSchema,
+ toFormAssignment,
+ TRoleAssignment
+} from "./roleAssignment";
+import { RoleAssignmentRow } from "./RoleAssignmentRow";
+import { useMemberRoleGrant } from "./useMemberRoleGrant";
type Props = {
projectMember: TWorkspaceUser;
@@ -92,120 +35,19 @@ export const MemberSingleRoleModify = ({
}: Props) => {
const { subscription } = useSubscription();
const { projectId, currentProject } = useProject();
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
- projectId,
- currentProject?.type
- );
- const { permission } = useProjectPermission();
- const isMemberEditDisabled = permission.cannot(
- ProjectPermissionMemberActions.Edit,
- ProjectPermissionSub.Member
- );
-
- const assignRoleConditions = useMemo(
- () => getMemberAssignRoleConditions(permission),
- [permission]
- );
-
- const canModifyMemberRoles = useMemo(() => {
- const memberEmail = projectMember?.user?.email;
- if (!memberEmail) return false;
-
- return canModifyByGrantConditions({
- targetValue: memberEmail,
- allowed: assignRoleConditions?.emails,
- forbidden: assignRoleConditions?.forbiddenEmails,
- isMatch: (value, pattern) => picomatch.isMatch(value, pattern)
- });
- }, [assignRoleConditions, projectMember?.user?.email]);
-
- const filteredRoles = useMemo(
- () =>
- filterByGrantConditions(projectRoles ?? [], {
- getKey: (r) => r.slug,
- allowed: assignRoleConditions?.roles,
- forbidden: assignRoleConditions?.forbiddenRoles
- }),
- [projectRoles, assignRoleConditions]
- );
-
- const assignableRoleSlugs = useMemo(
- () => new Set(filteredRoles.map((r) => r.slug)),
- [filteredRoles]
- );
-
- const getRolesForSelect = (currentSlug: string) => {
- const assignable = filteredRoles;
- const currentInAssignable = assignableRoleSlugs.has(currentSlug);
- if (currentInAssignable) return assignable;
-
- const currentRole = projectRoles?.find((r) => r.slug === currentSlug) ?? {
- slug: currentSlug,
- name: formatProjectRoleName(currentSlug),
- id: currentSlug
- };
- return [currentRole, ...assignable];
- };
-
- const isEditDisabled = isMemberEditDisabled || !canModifyMemberRoles;
-
- const roleForm = useForm<TRoleForm>({
- resolver: zodResolver(roleFormSchema),
- values: {
- slug: role.customRoleSlug || role.role,
- temporaryAccess: role.isTemporary
- ? {
- isTemporary: true,
- temporaryRange: role.temporaryRange,
- temporaryAccessEndTime: role.temporaryAccessEndTime,
- temporaryAccessStartTime: role.temporaryAccessStartTime
- }
- : {
- isTemporary: false
- }
- }
- });
-
- const temporaryAccess = roleForm.watch("temporaryAccess");
+ const { isRolesLoading, assignableRoleSlugs, getRolesForSelect, isEditDisabled } =
+ useMemberRoleGrant(projectMember);
const updateMembershipRole = useUpdateUserWorkspaceRole();
- const isTemporary = temporaryAccess?.isTemporary;
- const isExpired =
- temporaryAccess?.isTemporary &&
- new Date() > new Date(temporaryAccess.temporaryAccessEndTime || "");
-
- let durationVariant: "outline" | "warning" | "danger" = "outline";
- let text = "Permanent";
- let toolTipText = "Non-Expiring Access";
-
- if (isTemporary) {
- if (isExpired) {
- durationVariant = "danger";
- text = "Access Expired";
- toolTipText = "Timed Access Expired";
- } else {
- durationVariant = "warning";
- text = formatDistance(new Date(temporaryAccess.temporaryAccessEndTime || ""), new Date());
- toolTipText = `Until ${format(
- new Date(temporaryAccess.temporaryAccessEndTime || ""),
- "yyyy-MM-dd HH:mm:ss"
- )}`;
- }
- }
+ const roleForm = useForm<TRoleAssignment>({
+ resolver: zodResolver(roleAssignmentSchema),
+ values: toFormAssignment(role)
+ });
- const handleRoleUpdate = async (data: TRoleForm) => {
+ const handleRoleUpdate = async (data: TRoleAssignment) => {
if (updateMembershipRole.isPending) return;
- const nextRolePayload = data.temporaryAccess.isTemporary
- ? {
- role: data.slug,
- isTemporary: true as const,
- temporaryMode: ProjectUserMembershipTemporaryMode.Relative,
- temporaryRange: data.temporaryAccess.temporaryRange,
- temporaryAccessStartTime: data.temporaryAccess.temporaryAccessStartTime
- }
- : { role: data.slug, isTemporary: false as const };
-
+ const nextRolePayload = formRoleToPayload(data);
const hasCustomRoleSelected = !Object.values(ProjectMembershipRole).includes(
nextRolePayload.role as ProjectMembershipRole
);
@@ -215,30 +57,18 @@ export const MemberSingleRoleModify = ({
return;
}
- const sanitizedRoles = projectMember.roles.map((existing) => {
- if (existing.id !== role.id) {
- return existing.isTemporary
- ? {
- role: existing.role === "custom" ? existing.customRoleSlug : existing.role,
- isTemporary: true as const,
- temporaryMode: existing.temporaryMode,
- temporaryRange: existing.temporaryRange,
- temporaryAccessStartTime: existing.temporaryAccessStartTime
- }
- : {
- role: existing.role === "custom" ? existing.customRoleSlug : existing.role,
- isTemporary: false as const
- };
- }
- return nextRolePayload;
- });
+ // The PATCH replaces the whole role set, so re-send every current assignment and swap in the
+ // edited one — otherwise the member's other roles would be dropped.
+ const roles = projectMember.roles.map((existing) =>
+ existing.id === role.id ? nextRolePayload : existingRoleToPayload(existing)
+ );
const isCertManager = currentProject?.type === ProjectType.CertificateManager;
await updateMembershipRole.mutateAsync({
projectId,
projectType: currentProject?.type,
membershipId: isCertManager ? projectMember.user.id : projectMember.id,
- roles: sanitizedRoles
+ roles
});
createNotification({ text: "Successfully updated role", type: "success" });
onSuccess?.();
@@ -254,193 +84,17 @@ export const MemberSingleRoleModify = ({
return (
<form onSubmit={roleForm.handleSubmit(handleRoleUpdate)}>
- <div className="mt-2 flex items-end gap-2">
- <Controller
- control={roleForm.control}
- name="slug"
- render={({ field }) => {
- const rolesForSelect = getRolesForSelect(field.value);
- return (
- <Field className="min-w-0 flex-1">
- <FieldLabel>Role</FieldLabel>
- <Select
- value={field.value}
- onValueChange={field.onChange}
- disabled={isEditDisabled}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper" className="z-[70]">
- {rolesForSelect.map(({ name, slug, id: projectRoleId }) => {
- const isAssignable = assignableRoleSlugs.has(slug);
- return (
- <SelectItem
- value={slug}
- key={projectRoleId}
- disabled={!isAssignable}
- description={
- isAssignable
- ? undefined
- : "You don't have permission to assign this role"
- }
- >
- {name}
- </SelectItem>
- );
- })}
- </SelectContent>
- </Select>
- </Field>
- );
- }}
- />
- <Field className="w-44 shrink-0">
- <FieldLabel>Duration</FieldLabel>
- <Popover>
- <Tooltip>
- <TooltipTrigger asChild>
- <PopoverTrigger asChild>
- <Button
- type="button"
- variant={durationVariant}
- isDisabled={isEditDisabled}
- className="w-full capitalize"
- >
- {isTemporary && <ClockIcon />}
- {text}
- <ChevronDownIcon />
- </Button>
- </PopoverTrigger>
- </TooltipTrigger>
- <TooltipContent>{toolTipText}</TooltipContent>
- </Tooltip>
- <PopoverContent
- side="right"
- className="z-[70]"
- onWheel={(e) => e.stopPropagation()}
- onOpenAutoFocus={(e) => e.preventDefault()}
- >
- <div className="flex flex-col space-y-4">
- <div className="border-b border-b-border pb-2 text-sm text-muted">
- Configure Timed Access
- </div>
- {isExpired && <Badge variant="danger">Expired</Badge>}
- <Controller
- control={roleForm.control}
- defaultValue="1h"
- name="temporaryAccess.temporaryRange"
- render={({ field, fieldState: { error } }) => {
- const showInvalidError =
- Boolean(field.value) && !isValidTemporaryRange(field.value);
- const errorMessage = showInvalidError ? TEMPORARY_RANGE_ERROR : error?.message;
-
- return (
- <>
- <Field>
- <FieldLabel>
- <TtlFormLabel label="Validity" />
- </FieldLabel>
- <Input
- {...field}
- value={field.value ?? ""}
- isError={Boolean(errorMessage)}
- onChange={(e) => {
- field.onChange(e);
- const nextValue = e.target.value;
- if (!nextValue) {
- roleForm.setError(
- "temporaryAccess.temporaryRange",
- { type: "required", message: "Required" },
- { shouldFocus: false }
- );
- return;
- }
- if (!isValidTemporaryRange(nextValue)) {
- roleForm.setError(
- "temporaryAccess.temporaryRange",
- {
- type: "validate",
- message: TEMPORARY_RANGE_ERROR
- },
- { shouldFocus: false }
- );
- return;
- }
- roleForm.clearErrors("temporaryAccess.temporaryRange");
- }}
- />
- {errorMessage && <FieldError>{errorMessage}</FieldError>}
- </Field>
- <div className="flex items-center space-x-2">
- <Button
- size="xs"
- variant="outline"
- isDisabled={!isValidTemporaryRange(field.value)}
- onClick={() => {
- const temporaryRange = field.value;
- if (!isValidTemporaryRange(temporaryRange)) {
- roleForm.setError(
- "temporaryAccess.temporaryRange",
- {
- type: "validate",
- message: TEMPORARY_RANGE_ERROR
- },
- { shouldFocus: true }
- );
- return;
- }
- roleForm.clearErrors("temporaryAccess.temporaryRange");
- roleForm.setValue(
- "temporaryAccess",
- {
- isTemporary: true,
- temporaryAccessStartTime: new Date().toISOString(),
- temporaryRange,
- temporaryAccessEndTime: new Date(
- new Date().getTime() + ms(temporaryRange)
- ).toISOString()
- },
- { shouldDirty: true }
- );
- }}
- >
- {isTemporary ? "Restart" : "Grant"}
- </Button>
- {isTemporary && (
- <Button
- size="xs"
- variant="danger"
- onClick={() => {
- roleForm.setValue(
- "temporaryAccess",
- { isTemporary: false },
- { shouldDirty: true }
- );
- }}
- >
- Revoke Access
- </Button>
- )}
- </div>
- </>
- );
- }}
- />
- </div>
- </PopoverContent>
- </Popover>
- </Field>
- </div>
+ <RoleAssignmentRow
+ control={roleForm.control}
+ setValue={roleForm.setValue}
+ isEditDisabled={isEditDisabled}
+ assignableRoleSlugs={assignableRoleSlugs}
+ getRolesForSelect={getRolesForSelect}
+ />
<div className="mt-4 flex justify-end">
<Button
type="submit"
variant="project"
- className={twMerge(
- "transition-all",
- "cursor-default opacity-0",
- roleForm.formState.isDirty && "cursor-pointer opacity-100"
- )}
isDisabled={!roleForm.formState.isDirty || isEditDisabled}
isPending={roleForm.formState.isSubmitting}
>
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/RoleAssignmentRow.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/RoleAssignmentRow.tsx
new file mode 100644
index 0000000000..d8e3174ac0
--- /dev/null
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/RoleAssignmentRow.tsx
@@ -0,0 +1,203 @@
+import { ReactNode } from "react";
+import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form";
+import { ChevronDownIcon, ClockIcon } from "lucide-react";
+import ms from "ms";
+
+import { TtlFormLabel } from "@app/components/features";
+import {
+ Badge,
+ Button,
+ Field,
+ FieldError,
+ FieldLabel,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+
+import { getDurationDisplay, isValidTemporaryRange, TEMPORARY_RANGE_ERROR } from "./roleAssignment";
+
+type RoleForSelect = { slug: string; name: string; id: string };
+
+type Props = {
+ control: Control<any>;
+ setValue: UseFormSetValue<any>;
+ /** Field path prefix: "" for a flat single-role form, `roles.${index}.` for a multi-role array. */
+ namePrefix?: string;
+ /** Field editors stack rows; only the first row shows its labels. */
+ showLabels?: boolean;
+ isEditDisabled: boolean;
+ assignableRoleSlugs: Set<string>;
+ getRolesForSelect: (currentSlug: string) => RoleForSelect[];
+ /** Trailing control rendered after the duration field, e.g. a remove-row button. */
+ action?: ReactNode;
+};
+
+export const RoleAssignmentRow = ({
+ control,
+ setValue,
+ namePrefix = "",
+ showLabels = true,
+ isEditDisabled,
+ assignableRoleSlugs,
+ getRolesForSelect,
+ action
+}: Props) => {
+ const slugName = `${namePrefix}slug`;
+ const temporaryAccessName = `${namePrefix}temporaryAccess`;
+ const temporaryRangeName = `${namePrefix}temporaryAccess.temporaryRange`;
+
+ const temporaryAccess = useWatch({ control, name: temporaryAccessName });
+ const isTemporary = Boolean(temporaryAccess?.isTemporary);
+ const { variant, text, tooltip, isExpired } = getDurationDisplay(temporaryAccess);
+
+ return (
+ <div className="flex items-end gap-2">
+ <Controller
+ control={control}
+ name={slugName}
+ render={({ field }) => {
+ const rolesForSelect = getRolesForSelect(field.value);
+ return (
+ <Field className="min-w-0 flex-1">
+ {showLabels && <FieldLabel>Role</FieldLabel>}
+ <Select value={field.value} onValueChange={field.onChange} disabled={isEditDisabled}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper" className="z-[70]">
+ {rolesForSelect.map(({ name, slug, id }) => {
+ const isAssignable = assignableRoleSlugs.has(slug);
+ return (
+ <SelectItem
+ value={slug}
+ key={id}
+ disabled={!isAssignable}
+ description={
+ isAssignable ? undefined : "You don't have permission to assign this role"
+ }
+ >
+ {name}
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ </Field>
+ );
+ }}
+ />
+ <Field className="w-44 shrink-0">
+ {showLabels && <FieldLabel>Duration</FieldLabel>}
+ <Popover>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant={variant}
+ isDisabled={isEditDisabled}
+ className="w-full capitalize"
+ >
+ {isTemporary && <ClockIcon />}
+ {text}
+ <ChevronDownIcon />
+ </Button>
+ </PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent>{tooltip}</TooltipContent>
+ </Tooltip>
+ <PopoverContent
+ side="right"
+ className="z-[70]"
+ onWheel={(e) => e.stopPropagation()}
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ >
+ <div className="flex flex-col space-y-4">
+ <div className="border-b border-b-border pb-2 text-sm text-muted">
+ Configure Timed Access
+ </div>
+ {isExpired && <Badge variant="danger">Expired</Badge>}
+ <Controller
+ control={control}
+ defaultValue="1h"
+ name={temporaryRangeName}
+ render={({ field, fieldState: { error } }) => {
+ // The schema blocks an invalid range on save; this surfaces the same message
+ // while the user is still typing, before the value has been granted.
+ const isInvalid = Boolean(field.value) && !isValidTemporaryRange(field.value);
+ const errorMessage = isInvalid ? TEMPORARY_RANGE_ERROR : error?.message;
+
+ return (
+ <>
+ <Field>
+ <FieldLabel>
+ <TtlFormLabel label="Validity" />
+ </FieldLabel>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ isError={Boolean(errorMessage)}
+ />
+ {errorMessage && <FieldError>{errorMessage}</FieldError>}
+ </Field>
+ <div className="flex items-center space-x-2">
+ <Button
+ size="xs"
+ variant="outline"
+ isDisabled={!isValidTemporaryRange(field.value)}
+ onClick={() => {
+ const temporaryRange = field.value;
+ setValue(
+ temporaryAccessName,
+ {
+ isTemporary: true,
+ temporaryAccessStartTime: new Date().toISOString(),
+ temporaryRange,
+ temporaryAccessEndTime: new Date(
+ new Date().getTime() + ms(temporaryRange)
+ ).toISOString()
+ },
+ { shouldDirty: true }
+ );
+ }}
+ >
+ {isTemporary ? "Restart" : "Grant"}
+ </Button>
+ {isTemporary && (
+ <Button
+ size="xs"
+ variant="danger"
+ onClick={() =>
+ setValue(
+ temporaryAccessName,
+ { isTemporary: false },
+ { shouldDirty: true }
+ )
+ }
+ >
+ Revoke Access
+ </Button>
+ )}
+ </div>
+ </>
+ );
+ }}
+ />
+ </div>
+ </PopoverContent>
+ </Popover>
+ </Field>
+ {action}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/roleAssignment.ts b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/roleAssignment.ts
new file mode 100644
index 0000000000..657aeea591
--- /dev/null
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/roleAssignment.ts
@@ -0,0 +1,119 @@
+import { format, formatDistance } from "date-fns";
+import ms from "ms";
+import { z } from "zod";
+
+import {
+ ProjectUserMembershipTemporaryMode,
+ TUpdateWorkspaceUserRoleDTO
+} from "@app/hooks/api/projects/types";
+import { TWorkspaceUser } from "@app/hooks/api/types";
+
+export const TEMPORARY_RANGE_ERROR = "Only valid time values are accepted (1h, 20m, 2d).";
+
+export const isValidTemporaryRange = (value?: string) => {
+ if (!value?.trim()) return false;
+ const parsedMs = ms(value);
+ return typeof parsedMs === "number" && Number.isFinite(parsedMs) && parsedMs > 0;
+};
+
+// Shape of a single role assignment as edited in the form. The single-role editor uses this
+// directly; the multi-role editor nests it under `roles[]`. Pair the `temporaryRange` refine
+// with the Grant button's disabled state so an invalid duration can neither be granted nor saved.
+export const roleAssignmentSchema = z.object({
+ slug: z.string().min(1),
+ temporaryAccess: z.discriminatedUnion("isTemporary", [
+ z.object({
+ isTemporary: z.literal(true),
+ temporaryRange: z
+ .string()
+ .min(1, "Required")
+ .refine(isValidTemporaryRange, TEMPORARY_RANGE_ERROR),
+ temporaryAccessStartTime: z.string().datetime(),
+ temporaryAccessEndTime: z.string().datetime().nullable().optional()
+ }),
+ z.object({
+ isTemporary: z.literal(false)
+ })
+ ])
+});
+export type TRoleAssignment = z.infer<typeof roleAssignmentSchema>;
+export type TTemporaryAccess = TRoleAssignment["temporaryAccess"];
+
+export type MemberRoleAssignment = TWorkspaceUser["roles"][number];
+type TRolePayload = TUpdateWorkspaceUserRoleDTO["roles"][number];
+
+// A membership stores custom roles under `customRoleSlug` with `role === "custom"`; every other
+// role identifies itself by `role`.
+export const getRoleSlug = (assignment: Pick<MemberRoleAssignment, "role" | "customRoleSlug">) =>
+ assignment.role === "custom" ? (assignment.customRoleSlug ?? assignment.role) : assignment.role;
+
+export const toFormAssignment = (assignment: MemberRoleAssignment): TRoleAssignment => ({
+ slug: getRoleSlug(assignment),
+ temporaryAccess: assignment.isTemporary
+ ? {
+ isTemporary: true,
+ temporaryRange: assignment.temporaryRange,
+ temporaryAccessEndTime: assignment.temporaryAccessEndTime,
+ temporaryAccessStartTime: assignment.temporaryAccessStartTime
+ }
+ : { isTemporary: false }
+});
+
+export const formRoleToPayload = (assignment: TRoleAssignment): TRolePayload =>
+ assignment.temporaryAccess.isTemporary
+ ? {
+ role: assignment.slug,
+ isTemporary: true as const,
+ temporaryMode: ProjectUserMembershipTemporaryMode.Relative,
+ temporaryRange: assignment.temporaryAccess.temporaryRange,
+ temporaryAccessStartTime: assignment.temporaryAccess.temporaryAccessStartTime
+ }
+ : { role: assignment.slug, isTemporary: false as const };
+
+// An untouched assignment is re-sent as-is (preserving its own temporary mode) so a targeted
+// edit doesn't drop the member's other roles.
+export const existingRoleToPayload = (assignment: MemberRoleAssignment): TRolePayload =>
+ assignment.isTemporary
+ ? {
+ role: getRoleSlug(assignment),
+ isTemporary: true as const,
+ temporaryMode: assignment.temporaryMode,
+ temporaryRange: assignment.temporaryRange,
+ temporaryAccessStartTime: assignment.temporaryAccessStartTime
+ }
+ : { role: getRoleSlug(assignment), isTemporary: false as const };
+
+type TDurationDisplay = {
+ variant: "outline" | "warning" | "danger";
+ text: string;
+ tooltip: string;
+ isExpired: boolean;
+};
+
+export const getDurationDisplay = (temporaryAccess?: TTemporaryAccess): TDurationDisplay => {
+ if (!temporaryAccess?.isTemporary) {
+ return {
+ variant: "outline",
+ text: "Permanent",
+ tooltip: "Non-Expiring Access",
+ isExpired: false
+ };
+ }
+
+ const endTime = new Date(temporaryAccess.temporaryAccessEndTime || "");
+ if (new Date() > endTime) {
+ return {
+ variant: "danger",
+ text: "Access Expired",
+ tooltip: "Timed Access Expired",
+ isExpired: true
+ };
+ }
+
+ return {
+ variant: "warning",
+ text: formatDistance(endTime, new Date()),
+ tooltip: `Until ${format(endTime, "yyyy-MM-dd HH:mm:ss")}`,
+ isExpired: false
+ };
+};
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/useMemberRoleGrant.ts b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/useMemberRoleGrant.ts
new file mode 100644
index 0000000000..24a2a522a2
--- /dev/null
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/useMemberRoleGrant.ts
@@ -0,0 +1,86 @@
+import { useMemo } from "react";
+import picomatch from "picomatch";
+
+import {
+ ProjectPermissionMemberActions,
+ ProjectPermissionSub,
+ useProject,
+ useProjectPermission
+} from "@app/context";
+import { formatProjectRoleName } from "@app/helpers/roles";
+import { useGetProjectRoles } from "@app/hooks/api";
+import { TWorkspaceUser } from "@app/hooks/api/types";
+import {
+ canModifyByGrantConditions,
+ filterByGrantConditions,
+ getMemberAssignRoleConditions
+} from "@app/lib/fn/permission";
+
+// Resolves which project roles the current user may assign to `projectMember`, honouring the
+// grant conditions on their own permission (allowed/forbidden roles and target emails). Shared by
+// the single- and multi-role editors so both gate role selection the same way.
+export const useMemberRoleGrant = (projectMember: TWorkspaceUser) => {
+ const { projectId, currentProject } = useProject();
+ const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
+ projectId,
+ currentProject?.type
+ );
+ const { permission } = useProjectPermission();
+
+ const isMemberEditDisabled = permission.cannot(
+ ProjectPermissionMemberActions.Edit,
+ ProjectPermissionSub.Member
+ );
+
+ const assignRoleConditions = useMemo(
+ () => getMemberAssignRoleConditions(permission),
+ [permission]
+ );
+
+ const canModifyMemberRoles = useMemo(() => {
+ const memberEmail = projectMember?.user?.email;
+ if (!memberEmail) return false;
+
+ return canModifyByGrantConditions({
+ targetValue: memberEmail,
+ allowed: assignRoleConditions?.emails,
+ forbidden: assignRoleConditions?.forbiddenEmails,
+ isMatch: (value, pattern) => picomatch.isMatch(value, pattern)
+ });
+ }, [assignRoleConditions, projectMember?.user?.email]);
+
+ const filteredRoles = useMemo(
+ () =>
+ filterByGrantConditions(projectRoles ?? [], {
+ getKey: (role) => role.slug,
+ allowed: assignRoleConditions?.roles,
+ forbidden: assignRoleConditions?.forbiddenRoles
+ }),
+ [projectRoles, assignRoleConditions]
+ );
+
+ const assignableRoleSlugs = useMemo(
+ () => new Set(filteredRoles.map((role) => role.slug)),
+ [filteredRoles]
+ );
+
+ // The list to show in a role Select: the assignable roles, prepended with the currently
+ // assigned role when it isn't itself assignable (so it stays visible but disabled).
+ const getRolesForSelect = (currentSlug: string) => {
+ if (assignableRoleSlugs.has(currentSlug)) return filteredRoles;
+
+ const currentRole = projectRoles?.find((role) => role.slug === currentSlug) ?? {
+ slug: currentSlug,
+ name: formatProjectRoleName(currentSlug),
+ id: currentSlug
+ };
+ return [currentRole, ...filteredRoles];
+ };
+
+ return {
+ isRolesLoading,
+ assignableRoleSlugs,
+ getRolesForSelect,
+ isEditDisabled: isMemberEditDisabled || !canModifyMemberRoles
+ };
+};