Continue progress on role ui update

This commit is contained in:
Tuan Dang
2024-07-22 12:41:26 +07:00
parent 3731459e99
commit bd860e6c5a
13 changed files with 779 additions and 133 deletions

View File

@@ -100,7 +100,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
.trim()
.optional()
.refine(
(val) => typeof val === "undefined" || Object.keys(OrgMembershipRole).includes(val),
(val) => typeof val !== "undefined" && !Object.keys(OrgMembershipRole).includes(val),
"Please choose a different slug, the slug you have entered is reserved."
)
.refine((val) => typeof val === "undefined" || slugify(val) === val, {

View File

@@ -68,13 +68,22 @@ export const useUpdateOrgRole = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, orgId, permissions, ...dto }: TUpdateOrgRoleDTO) =>
apiRequest.patch(`/api/v1/organization/${orgId}/roles/${id}`, {
mutationFn: ({ id, orgId, permissions, ...dto }: TUpdateOrgRoleDTO) => {
console.log("update args: ", {
id,
orgId,
permissions,
...dto,
pack: permissions?.length ? packRules(permissions) : []
});
return apiRequest.patch(`/api/v1/organization/${orgId}/roles/${id}`, {
...dto,
permissions: permissions?.length ? packRules(permissions) : []
}),
onSuccess: (_, { orgId }) => {
});
},
onSuccess: (_, { id, orgId }) => {
queryClient.invalidateQueries(roleQueryKeys.getOrgRoles(orgId));
queryClient.invalidateQueries(roleQueryKeys.getOrgRole(orgId, id));
}
});
};
@@ -87,8 +96,9 @@ export const useDeleteOrgRole = () => {
apiRequest.delete(`/api/v1/organization/${orgId}/roles/${id}`, {
data: { orgId }
}),
onSuccess: (_, { orgId }) => {
onSuccess: (_, { id, orgId }) => {
queryClient.invalidateQueries(roleQueryKeys.getOrgRoles(orgId));
queryClient.invalidateQueries(roleQueryKeys.getOrgRole(orgId, id));
}
});
};

View File

@@ -94,10 +94,13 @@ export const useGetOrgRole = (orgId: string, roleId: string) =>
useQuery({
queryKey: roleQueryKeys.getOrgRole(orgId, roleId),
queryFn: async () => {
const { data } = await apiRequest.get<{ role: TProjectRole }>(
`/api/v1/organization/${orgId}/roles/${roleId}` // TODO: implement
);
return data.role;
const { data } = await apiRequest.get<{
role: Omit<TOrgRole, "permissions"> & { permissions: unknown };
}>(`/api/v1/organization/${orgId}/roles/${roleId}`);
return {
...data.role,
permissions: unpackRules(data.role.permissions as PackRule<TPermission>[])
};
},
enabled: Boolean(orgId && roleId)
});

View File

@@ -106,8 +106,6 @@ const SIMPLE_PERMISSION_OPTIONS = [
export const OrgRoleModifySection = ({ role, onGoBack }: Props) => {
const isNonEditable = ["owner", "admin", "member", "no-access"].includes(role?.slug || "");
const isNewRole = !role?.slug;
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
const {

View File

@@ -18,29 +18,15 @@ import {
} from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
import { withPermission } from "@app/hoc";
import {
// useDeleteIdentity,
// useGetIdentityById,
// useRevokeIdentityTokenAuthToken,
// useRevokeIdentityUniversalAuthClientSecret,
useGetOrgRole
} from "@app/hooks/api";
import { useGetOrgRole } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
import { RolePermissionsTable } from "./components/RolePermissionsSection/RolePermissionsTable";
import { RoleDetailsSection, RolePermissionsSection } from "./components";
// import { IdentityAuthMethodModal } from "../MembersPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModal";
// import { IdentityModal } from "../MembersPage/components/OrgIdentityTab/components/IdentitySection/IdentityModal";
// import { IdentityUniversalAuthClientSecretModal } from "../MembersPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthClientSecretModal";
// import {
// IdentityAuthenticationSection,
// IdentityClientSecretModal,
// IdentityDetailsSection,
// IdentityProjectsSection,
// IdentityTokenListModal,
// IdentityTokenModal
// } from "./components";
import {
RoleDetailsSection,
RoleModal,
RolePermissionModal,
RolePermissionsSection} from "./components";
export const RolePage = withPermission(
() => {
@@ -57,17 +43,8 @@ export const RolePage = withPermission(
// const { mutateAsync: revokeClientSecret } = useRevokeIdentityUniversalAuthClientSecret();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"identity",
"deleteIdentity",
"identityAuthMethod",
"revokeAuthMethod",
"token",
"tokenList",
"revokeToken",
"clientSecret",
"revokeClientSecret",
"universalAuthClientSecret", // list of client secrets
"upgradePlan"
"role",
"rolePermission"
] as const);
// const onDeleteIdentitySubmit = async (id: string) => {
@@ -202,10 +179,12 @@ export const RolePage = withPermission(
<div className="mr-4 w-96">
<RoleDetailsSection roleId={roleId} handlePopUpOpen={handlePopUpOpen} />
</div>
<RolePermissionsSection />
<RolePermissionsSection roleId={roleId} handlePopUpOpen={handlePopUpOpen} />
</div>
</div>
)}
<RoleModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<RolePermissionModal roleId={roleId} popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
{/* <IdentityModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<IdentityAuthMethodModal
popUp={popUp}

View File

@@ -3,17 +3,17 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { OrgPermissionCan } from "@app/components/permissions";
import { IconButton, Tooltip } from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects,useOrganization } from "@app/context";
import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
import { useTimedReset } from "@app/hooks";
import { useGetOrgRole } from "@app/hooks/api";
// import { UsePopUpState } from "@app/hooks/usePopUp";
import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
roleId: string;
// handlePopUpOpen: (popUpName: keyof UsePopUpState<[]>, data?: {}) => void;
handlePopUpOpen: (popUpName: keyof UsePopUpState<["role"]>, data?: {}) => void;
};
export const RoleDetailsSection = ({ roleId }: Props) => {
export const RoleDetailsSection = ({ roleId, handlePopUpOpen }: Props) => {
const [copyTextId, isCopyingId, setCopyTextId] = useTimedReset<string>({
initialState: "Copy ID to clipboard"
});
@@ -22,8 +22,6 @@ export const RoleDetailsSection = ({ roleId }: Props) => {
const orgId = currentOrg?.id || "";
const { data } = useGetOrgRole(orgId, roleId);
console.log("useGetOrgRole data: ", data);
return data ? (
<div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<div className="flex items-center justify-between border-b border-mineshaft-400 pb-4">
@@ -37,14 +35,11 @@ export const RoleDetailsSection = ({ roleId }: Props) => {
ariaLabel="copy icon"
variant="plain"
className="group relative"
onClick={() => {
// handlePopUpOpen("identity", {
// identityId,
// name: data.identity.name,
// role: data.role,
// customRole: data.customRole
// });
}}
onClick={() =>
handlePopUpOpen("role", {
roleId
})
}
>
<FontAwesomeIcon icon={faPencil} />
</IconButton>
@@ -79,6 +74,14 @@ export const RoleDetailsSection = ({ roleId }: Props) => {
<p className="text-sm font-semibold text-mineshaft-300">Name</p>
<p className="text-sm text-mineshaft-300">{data.name}</p>
</div>
<div className="mb-4">
<p className="text-sm font-semibold text-mineshaft-300">Slug</p>
<p className="text-sm text-mineshaft-300">{data.slug}</p>
</div>
<div className="mb-4">
<p className="text-sm font-semibold text-mineshaft-300">Description</p>
<p className="text-sm text-mineshaft-300">{data.description}</p>
</div>
</div>
</div>
) : (

View File

@@ -1,4 +1,4 @@
// import { useEffect } from "react";
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
@@ -7,11 +7,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
import { useOrganization } from "@app/context";
import {
useGetOrgRole
// useCreateOrgRole,
// useUpdateOrgRole
} from "@app/hooks/api";
import { useGetOrgRole, useUpdateOrgRole } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
const schema = z
@@ -37,26 +33,22 @@ type Props = {
handlePopUpToggle: (popUpName: keyof UsePopUpState<["role"]>, state?: boolean) => void;
};
export const RoleDetailsModal = ({ popUp, handlePopUpToggle }: Props) => {
export const RoleModal = ({ popUp, handlePopUpToggle }: Props) => {
// const router = useRouter();
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
const role = popUp?.role?.data as {
const popupData = popUp?.role?.data as {
roleId: string;
};
const { data } = useGetOrgRole(orgId, role.roleId ?? "");
console.log("RoleDetailsModal: useGetOrgRole data: ", data);
// TODO: fetch by role id here
const { data: role } = useGetOrgRole(orgId, popupData?.roleId ?? "");
// const { mutateAsync: createMutateAsync } = useCreateIdentity();
// const { mutateAsync: updateMutateAsync } = useUpdateIdentity();
// const { mutateAsync: addMutateAsync } = useAddIdentityUniversalAuth();
// const { mutateAsync: createOrgRole } = useCreateOrgRole();
// const { mutateAsync: updateOrgRole } = useUpdateOrgRole();
const { mutateAsync: updateOrgRole } = useUpdateOrgRole();
const {
control,
@@ -71,21 +63,21 @@ export const RoleDetailsModal = ({ popUp, handlePopUpToggle }: Props) => {
}
});
// useEffect(() => {
// if (role) {
// reset({
// name: role.name,
// description: role.description,
// slug: role.slug
// });
// } else {
// reset({
// name: "",
// description: "",
// slug: ""
// });
// }
// }, [role]);
useEffect(() => {
if (role) {
reset({
name: role.name,
description: role.description,
slug: role.slug
});
} else {
reset({
name: "",
description: "",
slug: ""
});
}
}, [role]);
const onFormSubmit = async ({ name, description, slug }: FormData) => {
try {
@@ -95,23 +87,22 @@ export const RoleDetailsModal = ({ popUp, handlePopUpToggle }: Props) => {
slug
});
if (!orgId) return;
if (role) {
// update
// const up = await updateOrgRole({});
// console.log("onFormSubmit up: ", up);
// await updateMutateAsync({
// identityId: identity.identityId,
// name,
// role: role || undefined,
// organizationId: orgId
// });
await updateOrgRole({
orgId,
id: role.id,
name,
description,
slug
});
handlePopUpToggle("role", false);
} else {
// create
// TODO: create
// const { id: createdId } = await createMutateAsync({
// name,
@@ -119,16 +110,6 @@ export const RoleDetailsModal = ({ popUp, handlePopUpToggle }: Props) => {
// organizationId: orgId
// });
// await addMutateAsync({
// organizationId: orgId,
// identityId: createdId,
// clientSecretTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
// accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
// accessTokenTTL: 2592000,
// accessTokenMaxTTL: 2592000,
// accessTokenNumUsesLimit: 0
// });
handlePopUpToggle("role", false);
// router.push(`/org/${orgId}/identities/${createdId}`);
}
@@ -168,7 +149,12 @@ export const RoleDetailsModal = ({ popUp, handlePopUpToggle }: Props) => {
defaultValue=""
name="name"
render={({ field, fieldState: { error } }) => (
<FormControl label="Name" isError={Boolean(error)} errorText={error?.message}>
<FormControl
label="Name"
isError={Boolean(error)}
errorText={error?.message}
isRequired
>
<Input {...field} placeholder="Billing Team" />
</FormControl>
)}
@@ -178,7 +164,12 @@ export const RoleDetailsModal = ({ popUp, handlePopUpToggle }: Props) => {
defaultValue=""
name="slug"
render={({ field, fieldState: { error } }) => (
<FormControl label="Slug" isError={Boolean(error)} errorText={error?.message}>
<FormControl
label="Slug"
isError={Boolean(error)}
errorText={error?.message}
isRequired
>
<Input {...field} placeholder="billing" />
</FormControl>
)}

View File

@@ -0,0 +1,350 @@
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Button,
Checkbox,
FormControl,
Modal,
ModalContent,
Select,
SelectItem
} from "@app/components/v2";
import { useOrganization } from "@app/context";
import { useGetOrgRole } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
enum Permission {
NoAccess = "no-access",
ReadOnly = "read-only",
FullAccess = "full-acess",
Custom = "custom"
}
const generalPermissionSchema = z
.object({
read: z.boolean().optional(),
edit: z.boolean().optional(),
delete: z.boolean().optional(),
create: z.boolean().optional()
})
.optional();
const specificPermissionSchemas = {
workspace: z
.object({
read: z.boolean().optional(),
create: z.boolean().optional()
})
.optional(),
member: generalPermissionSchema,
groups: generalPermissionSchema,
role: generalPermissionSchema,
settings: generalPermissionSchema,
"service-account": generalPermissionSchema,
"incident-contact": generalPermissionSchema,
"secret-scanning": generalPermissionSchema,
sso: generalPermissionSchema,
scim: generalPermissionSchema,
ldap: generalPermissionSchema,
billing: generalPermissionSchema,
identity: generalPermissionSchema
};
// Create a union of all possible keys
const permissionsUnion = z.union([
z.object({ workspace: specificPermissionSchemas.workspace }),
z.object({ member: specificPermissionSchemas.member }),
z.object({ groups: specificPermissionSchemas.groups }),
z.object({ role: specificPermissionSchemas.role }),
z.object({ settings: specificPermissionSchemas.settings }),
z.object({ "service-account": specificPermissionSchemas["service-account"] }),
z.object({ "incident-contact": specificPermissionSchemas["incident-contact"] }),
z.object({ "secret-scanning": specificPermissionSchemas["secret-scanning"] }),
z.object({ sso: specificPermissionSchemas.sso }),
z.object({ scim: specificPermissionSchemas.scim }),
z.object({ ldap: specificPermissionSchemas.ldap }),
z.object({ billing: specificPermissionSchemas.billing }),
z.object({ identity: specificPermissionSchemas.identity })
]);
const schema = z.object({
resource: z.string(), // this is formName
action: z.nativeEnum(Permission),
permissions: z.record(z.string(), permissionsUnion).optional()
});
type FormData = z.infer<typeof schema>;
type Props = {
roleId: string;
popUp: UsePopUpState<["rolePermission"]>;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["rolePermission"]>, state?: boolean) => void;
};
const SIMPLE_PERMISSION_OPTIONS = [
{
title: "User management",
formName: "member"
},
{
title: "Group management",
formName: "groups"
},
{
title: "Machine identity management",
formName: "identity"
},
{
title: "Billing & usage",
formName: "billing"
},
{
title: "Role management",
formName: "role"
},
{
title: "Incident Contacts",
formName: "incident-contact"
},
{
title: "Organization profile",
formName: "settings"
},
{
title: "Secret Scanning",
formName: "secret-scanning"
},
{
title: "SSO",
formName: "sso"
},
{
title: "LDAP",
formName: "ldap"
},
{
title: "SCIM",
formName: "scim"
}
] as const;
const PERMISSIONS = [
{ action: "read", label: "View" },
{ action: "create", label: "Create" },
{ action: "edit", label: "Modify" },
{ action: "delete", label: "Remove" }
] as const;
const SECRET_SCANNING_PERMISSIONS = [
{ action: "read", label: "View risks" },
{ action: "create", label: "Add integrations" },
{ action: "edit", label: "Edit risk status" },
{ action: "delete", label: "Remove integrations" }
] as const;
const INCIDENT_CONTACTS_PERMISSIONS = [
{ action: "read", label: "View contacts" },
{ action: "create", label: "Add new contacts" },
{ action: "edit", label: "Edit contacts" },
{ action: "delete", label: "Remove contacts" }
] as const;
const MEMBERS_PERMISSIONS = [
{ action: "read", label: "View all members" },
{ action: "create", label: "Invite members" },
{ action: "edit", label: "Edit members" },
{ action: "delete", label: "Remove members" }
] as const;
const BILLING_PERMISSIONS = [
{ action: "read", label: "View bills" },
{ action: "create", label: "Add payment methods" },
{ action: "edit", label: "Edit payments" },
{ action: "delete", label: "Remove payments" }
] as const;
const getPermissionList = (option: string) => {
switch (option) {
case "secret-scanning":
return SECRET_SCANNING_PERMISSIONS;
case "billing":
return BILLING_PERMISSIONS;
case "incident-contact":
return INCIDENT_CONTACTS_PERMISSIONS;
case "member":
return MEMBERS_PERMISSIONS;
default:
return PERMISSIONS;
}
};
export const RolePermissionModal = ({ roleId, popUp, handlePopUpToggle }: Props) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
const { data: role } = useGetOrgRole(orgId, roleId);
const {
control,
handleSubmit,
reset,
formState: { isSubmitting },
watch
} = useForm<FormData>({
resolver: zodResolver(schema)
});
const resource = watch("resource");
const action = watch("action");
useEffect(() => {
reset({
resource: SIMPLE_PERMISSION_OPTIONS[0].formName,
action: Permission.NoAccess
});
// TODO: update for existing permission
// if (role) {
// console.log("existing role found: ", role);
// reset({
// resource: SIMPLE_PERMISSION_OPTIONS[0].formName
// });
// } else {
// console.log("no role found");
// reset({
// resource: SIMPLE_PERMISSION_OPTIONS[0].formName
// });
// }
}, [role]);
const onFormSubmit = async () => {
try {
// TODO: map action to permission array?
// TODO: add permission to role
// await addIdentityToWorkspace({
// workspaceId,
// identityId,
// role: role || undefined
// });
createNotification({
text: "Successfully added permission to role",
type: "success"
});
// reset();
// handlePopUpToggle("rolePermission", false);
} catch (err) {
console.error(err);
const error = err as any;
const text = error?.response?.data?.message ?? "Failed to add identity to project";
createNotification({
text,
type: "error"
});
}
};
return (
<Modal
isOpen={popUp?.rolePermission?.isOpen}
onOpenChange={(isOpen) => {
handlePopUpToggle("rolePermission", isOpen);
reset();
}}
>
<ModalContent title="Add Permission to Role">
<form onSubmit={handleSubmit(onFormSubmit)}>
<Controller
control={control}
name="resource"
defaultValue=""
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl label="Resource" errorText={error?.message} isError={Boolean(error)}>
<Select
defaultValue={field.value}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full"
>
{SIMPLE_PERMISSION_OPTIONS.map(({ title, formName }) => (
<SelectItem value={formName} key={`resource-${title}`}>
{title}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
<Controller
control={control}
name="action"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl label="Action" errorText={error?.message} isError={Boolean(error)}>
<Select
defaultValue={field.value}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full"
>
<SelectItem value={Permission.NoAccess}>No Access</SelectItem>
<SelectItem value={Permission.ReadOnly}>Read Only</SelectItem>
<SelectItem value={Permission.FullAccess}>Full Access</SelectItem>
<SelectItem value={Permission.Custom}>Custom</SelectItem>
</Select>
</FormControl>
)}
/>
{action === Permission.Custom && (
<div className="mt-8 mb-4 grid grid-cols-3 gap-4">
{getPermissionList(watch("resource")).map((p) => {
return (
<Controller
name={`permissions.${resource}.${p.action}`}
key={`permissions.${resource}.${p.action}`}
control={control}
render={({ field }) => (
<Checkbox
isChecked
onCheckedChange={field.onChange}
id={`permissions.${resource}.${p.action}`}
isDisabled={false}
>
{p.label}
</Checkbox>
)}
/>
);
})}
</div>
)}
<div className="mt-8 flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
isLoading={isSubmitting}
isDisabled={isSubmitting}
>
Add
</Button>
<Button
colorSchema="secondary"
variant="plain"
onClick={() => handlePopUpToggle("rolePermission", false)}
>
Cancel
</Button>
</div>
</form>
</ModalContent>
</Modal>
);
};

View File

@@ -0,0 +1,215 @@
import { useEffect, useMemo } from "react";
import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form";
import { faChevronDown, faChevronRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { createNotification } from "@app/components/notifications";
import { Checkbox, IconButton, Select, SelectItem,Td, Tr } from "@app/components/v2";
import { useToggle } from "@app/hooks";
import { TFormSchema } from "@app/views/Org/MembersPage/components/OrgRoleTabSection/OrgRoleModifySection/OrgRoleModifySection.utils";
const PERMISSIONS = [
{ action: "read", label: "View" },
{ action: "create", label: "Create" },
{ action: "edit", label: "Modify" },
{ action: "delete", label: "Remove" }
] as const;
const SECRET_SCANNING_PERMISSIONS = [
{ action: "read", label: "View risks" },
{ action: "create", label: "Add integrations" },
{ action: "edit", label: "Edit risk status" },
{ action: "delete", label: "Remove integrations" }
] as const;
const INCIDENT_CONTACTS_PERMISSIONS = [
{ action: "read", label: "View contacts" },
{ action: "create", label: "Add new contacts" },
{ action: "edit", label: "Edit contacts" },
{ action: "delete", label: "Remove contacts" }
] as const;
const MEMBERS_PERMISSIONS = [
{ action: "read", label: "View all members" },
{ action: "create", label: "Invite members" },
{ action: "edit", label: "Edit members" },
{ action: "delete", label: "Remove members" }
] as const;
const BILLING_PERMISSIONS = [
{ action: "read", label: "View bills" },
{ action: "create", label: "Add payment methods" },
{ action: "edit", label: "Edit payments" },
{ action: "delete", label: "Remove payments" }
] as const;
const getPermissionList = (option: string) => {
switch (option) {
case "secret-scanning":
return SECRET_SCANNING_PERMISSIONS;
case "billing":
return BILLING_PERMISSIONS;
case "incident-contact":
return INCIDENT_CONTACTS_PERMISSIONS;
case "member":
return MEMBERS_PERMISSIONS;
default:
return PERMISSIONS;
}
};
type Props = {
title: string;
formName: keyof Omit<Exclude<TFormSchema["permissions"], undefined>, "workspace">;
setValue: UseFormSetValue<TFormSchema>;
control: Control<TFormSchema>;
};
// permission categories
enum Permission {
NoAccess = "no-access",
ReadOnly = "read-only",
FullAccess = "full-acess",
Custom = "custom"
}
// TODO: support for default roles
export const RolePermissionRow2 = ({ title, formName, control, setValue }: Props) => {
const [isRowExpanded, setIsRowExpanded] = useToggle();
const [isCustom, setIsCustom] = useToggle();
const rule = useWatch({
control,
name: `permissions.${formName}`
});
const selectedPermissionCategory = useMemo(() => {
const actions = Object.keys(rule || {}) as Array<keyof typeof rule>;
const totalActions = PERMISSIONS.length;
const score = actions.map((key) => (rule?.[key] ? 1 : 0)).reduce((a, b) => a + b, 0 as number);
if (isCustom) return Permission.Custom;
if (score === 0) return Permission.NoAccess;
if (score === totalActions) return Permission.FullAccess;
if (score === 1 && rule?.read) return Permission.ReadOnly;
return Permission.Custom;
}, [rule, isCustom]);
useEffect(() => {
if (selectedPermissionCategory === Permission.Custom) setIsCustom.on();
else setIsCustom.off();
}, [selectedPermissionCategory]);
useEffect(() => {
const isRowCustom = selectedPermissionCategory === Permission.Custom;
if (isRowCustom) {
setIsRowExpanded.on();
}
}, []);
const handlePermissionChange = (val: Permission) => {
// TODO: trigger update
if (val === Permission.Custom) {
setIsRowExpanded.on();
setIsCustom.on();
return;
}
setIsCustom.off();
switch (val) {
case Permission.NoAccess:
setValue(
`permissions.${formName}`,
{ read: false, edit: false, create: false, delete: false },
{ shouldDirty: true }
);
break;
case Permission.FullAccess:
setValue(
`permissions.${formName}`,
{ read: true, edit: true, create: true, delete: true },
{ shouldDirty: true }
);
break;
case Permission.ReadOnly:
setValue(
`permissions.${formName}`,
{ read: true, edit: false, create: false, delete: false },
{ shouldDirty: true }
);
break;
default:
setValue(
`permissions.${formName}`,
{ read: false, edit: false, create: false, delete: false },
{ shouldDirty: true }
);
break;
}
createNotification({ type: "success", text: "Updated permission on role." });
};
return (
<>
<Tr>
<Td>
<IconButton
ariaLabel="copy icon"
variant="plain"
className="group relative ml-2"
onClick={() => setIsRowExpanded.toggle()}
>
<FontAwesomeIcon icon={isRowExpanded ? faChevronDown : faChevronRight} />
</IconButton>
</Td>
<Td>{title}</Td>
<Td>
<Select
value={selectedPermissionCategory}
className="w-40 bg-mineshaft-600"
dropdownContainerClassName="border border-mineshaft-600 bg-mineshaft-800"
onValueChange={handlePermissionChange}
>
<SelectItem value={Permission.NoAccess}>No Access</SelectItem>
<SelectItem value={Permission.ReadOnly}>Read Only</SelectItem>
<SelectItem value={Permission.FullAccess}>Full Access</SelectItem>
<SelectItem value={Permission.Custom}>Custom</SelectItem>
</Select>
</Td>
</Tr>
{isRowExpanded && (
<Tr>
<Td
colSpan={3}
className={`bg-bunker-600 px-0 py-0 ${isRowExpanded && " border-mineshaft-500 p-8"}`}
>
<div className="grid grid-cols-3 gap-4">
{getPermissionList(formName).map(({ action, label }) => {
return (
<Controller
name={`permissions.${formName}.${action}`}
key={`permissions.${formName}.${action}`}
control={control}
render={({ field }) => (
<Checkbox
isChecked={field.value}
onCheckedChange={field.onChange}
id={`permissions.${formName}.${action}`}
>
{label}
</Checkbox>
)}
/>
);
})}
</div>
</Td>
</Tr>
)}
</>
);
};

View File

@@ -1,20 +1,15 @@
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
// import { UsePopUpState } from "@app/hooks/usePopUp";
import { RolePermissionsTable2 } from "./RolePermissionsTable2";
// import { createNotification } from "@app/components/notifications";
import {
// DeleteActionModal,
IconButton
} from "@app/components/v2";
type Props = {
roleId: string;
// handlePopUpOpen: (popUpName: keyof UsePopUpState<["rolePermission"]>, data?: {}) => void;
};
import { RolePermissionsTable } from "./RolePermissionsTable";
// import { useDeleteIdentityFromWorkspace } from "@app/hooks/api";
// import { usePopUp } from "@app/hooks/usePopUp";
// import { IdentityAddToProjectModal } from "./IdentityAddToProjectModal";
// import { IdentityProjectsTable } from "./IdentityProjectsTable";
export const RolePermissionsSection = () => {
export const RolePermissionsSection = ({
roleId
}: // handlePopUpOpen
Props) => {
// const { mutateAsync: deleteMutateAsync } = useDeleteIdentityFromWorkspace();
// const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
@@ -51,20 +46,18 @@ export const RolePermissionsSection = () => {
<div className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<div className="flex items-center justify-between border-b border-mineshaft-400 pb-4">
<h3 className="text-lg font-semibold text-mineshaft-100">Permissions</h3>
<IconButton
{/* <IconButton
ariaLabel="copy icon"
variant="plain"
className="group relative"
onClick={() => {
console.log("TODO");
// handlePopUpOpen("addIdentityToProject");
}}
onClick={() => handlePopUpOpen("rolePermission")}
>
<FontAwesomeIcon icon={faPlus} />
</IconButton>
</IconButton> */}
</div>
<div className="py-4">
<RolePermissionsTable />
{/* <RolePermissionsTable /> */}
<RolePermissionsTable2 roleId={roleId} />
{/* <IdentityProjectsTable identityId={identityId} handlePopUpOpen={handlePopUpOpen} /> */}
</div>
{/* <DeleteActionModal

View File

@@ -0,0 +1,103 @@
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Table, TableContainer, TBody, Th, THead, Tr } from "@app/components/v2";
import { useOrganization } from "@app/context";
import { useGetOrgRole } from "@app/hooks/api";
// TODO: consider moving this out
import {
formSchema,
rolePermission2Form,
TFormSchema} from "@app/views/Org/MembersPage/components/OrgRoleTabSection/OrgRoleModifySection/OrgRoleModifySection.utils";
import { RolePermissionRow2 } from "./RolePermissionRow2";
const SIMPLE_PERMISSION_OPTIONS = [
{
title: "User management",
formName: "member"
},
{
title: "Group management",
formName: "groups"
},
{
title: "Machine identity management",
formName: "identity"
},
{
title: "Billing & usage",
formName: "billing"
},
{
title: "Role management",
formName: "role"
},
{
title: "Incident Contacts",
formName: "incident-contact"
},
{
title: "Organization profile",
formName: "settings"
},
{
title: "Secret Scanning",
formName: "secret-scanning"
},
{
title: "SSO",
formName: "sso"
},
{
title: "LDAP",
formName: "ldap"
},
{
title: "SCIM",
formName: "scim"
}
] as const;
type Props = {
roleId: string;
};
export const RolePermissionsTable2 = ({ roleId }: Props) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
const { data: role } = useGetOrgRole(orgId, roleId);
const { setValue, control } = useForm<TFormSchema>({
defaultValues: role ? { ...role, permissions: rolePermission2Form(role.permissions) } : {},
resolver: zodResolver(formSchema)
});
return (
<TableContainer>
<Table>
<THead>
<Tr>
<Th className="w-5" />
<Th>Resource</Th>
<Th>Permission</Th>
</Tr>
</THead>
<TBody>
{SIMPLE_PERMISSION_OPTIONS.map((permission) => {
return (
<RolePermissionRow2
title={permission.title}
formName={permission.formName}
control={control}
setValue={setValue}
key={`org-role-${roleId}-permission-${permission.formName}`}
/>
);
})}
</TBody>
</Table>
</TableContainer>
);
};

View File

@@ -1,2 +1,4 @@
export { RoleDetailsSection } from "./RoleDetailsSection";
export { RoleModal } from "./RoleModal";
export { RolePermissionModal } from "./RolePermissionModal";
export { RolePermissionsSection } from "./RolePermissionsSection";

View File

@@ -161,7 +161,6 @@ export const SecretOverviewTableRow = ({
secretPath={secretPath}
getSecretByKey={getSecretByKey}
/>
<TableContainer>
<table className="secret-table">
<thead>