Clean org roles concept refactor

This commit is contained in:
Tuan Dang
2024-07-22 16:56:27 +07:00
parent bd860e6c5a
commit b64d4e57c4
12 changed files with 222 additions and 847 deletions
@@ -3,8 +3,7 @@ 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 { 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";
@@ -63,6 +62,7 @@ type Props = {
formName: keyof Omit<Exclude<TFormSchema["permissions"], undefined>, "workspace">;
setValue: UseFormSetValue<TFormSchema>;
control: Control<TFormSchema>;
handleSubmit: () => void;
};
// permission categories
@@ -76,7 +76,7 @@ enum Permission {
// TODO: support for default roles
export const RolePermissionRow2 = ({ title, formName, control, setValue }: Props) => {
export const RolePermissionRow = ({ title, formName, handleSubmit, control, setValue }: Props) => {
const [isRowExpanded, setIsRowExpanded] = useToggle();
const [isCustom, setIsCustom] = useToggle();
@@ -111,7 +111,6 @@ export const RolePermissionRow2 = ({ title, formName, control, setValue }: Props
}, []);
const handlePermissionChange = (val: Permission) => {
// TODO: trigger update
if (val === Permission.Custom) {
setIsRowExpanded.on();
setIsCustom.on();
@@ -150,12 +149,15 @@ export const RolePermissionRow2 = ({ title, formName, control, setValue }: Props
break;
}
createNotification({ type: "success", text: "Updated permission on role." });
handleSubmit();
};
return (
<>
<Tr>
<Tr
className="h-10 cursor-pointer transition-colors duration-300 hover:bg-mineshaft-700"
onClick={() => setIsRowExpanded.toggle()}
>
<Td>
<IconButton
ariaLabel="copy icon"
@@ -197,7 +199,10 @@ export const RolePermissionRow2 = ({ title, formName, control, setValue }: Props
render={({ field }) => (
<Checkbox
isChecked={field.value}
onCheckedChange={field.onChange}
onCheckedChange={(e) => {
field.onChange(e);
handleSubmit();
}}
id={`permissions.${formName}.${action}`}
>
{label}
@@ -1,88 +1,18 @@
// import { UsePopUpState } from "@app/hooks/usePopUp";
import { RolePermissionsTable2 } from "./RolePermissionsTable2";
import { RolePermissionsTable } from "./RolePermissionsTable";
type Props = {
roleId: string;
// handlePopUpOpen: (popUpName: keyof UsePopUpState<["rolePermission"]>, data?: {}) => void;
};
export const RolePermissionsSection = ({
roleId
}: // handlePopUpOpen
Props) => {
// const { mutateAsync: deleteMutateAsync } = useDeleteIdentityFromWorkspace();
// const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
// "addIdentityToProject",
// "removeIdentityFromProject"
// ] as const);
// const onRemoveIdentitySubmit = async (id: string, projectId: string) => {
// try {
// await deleteMutateAsync({
// identityId: id,
// workspaceId: projectId
// });
// createNotification({
// text: "Successfully removed identity from project",
// type: "success"
// });
// handlePopUpClose("removeIdentityFromProject");
// } catch (err) {
// console.error(err);
// const error = err as any;
// const text = error?.response?.data?.message ?? "Failed to remove identity from project";
// createNotification({
// text,
// type: "error"
// });
// }
// };
export const RolePermissionsSection = ({ roleId }: Props) => {
return (
<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
ariaLabel="copy icon"
variant="plain"
className="group relative"
onClick={() => handlePopUpOpen("rolePermission")}
>
<FontAwesomeIcon icon={faPlus} />
</IconButton> */}
</div>
<div className="py-4">
{/* <RolePermissionsTable /> */}
<RolePermissionsTable2 roleId={roleId} />
{/* <IdentityProjectsTable identityId={identityId} handlePopUpOpen={handlePopUpOpen} /> */}
<RolePermissionsTable roleId={roleId} />
</div>
{/* <DeleteActionModal
isOpen={popUp.removeIdentityFromProject.isOpen}
title={`Are you sure want to remove ${
(popUp?.removeIdentityFromProject?.data as { identityName: string })?.identityName || ""
} from ${
(popUp?.removeIdentityFromProject?.data as { projectName: string })?.projectName || ""
}?`}
onChange={(isOpen) => handlePopUpToggle("removeIdentityFromProject", isOpen)}
deleteKey="confirm"
onDeleteApproved={() => {
const popupData = popUp?.removeIdentityFromProject?.data as {
identityId: string;
projectId: string;
};
return onRemoveIdentitySubmit(popupData.identityId, popupData.projectId);
}}
/> */}
{/* <IdentityAddToProjectModal
identityId={identityId}
popUp={popUp}
handlePopUpToggle={handlePopUpToggle}
/> */}
</div>
);
};
@@ -1,124 +1,125 @@
import { faEllipsis } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { OrgPermissionCan } from "@app/components/permissions";
import { createNotification } from "@app/components/notifications";
import { Table, TableContainer, TBody, Th, THead, Tr } from "@app/components/v2";
import { useOrganization } from "@app/context";
import { useGetOrgRole, useUpdateOrgRole } from "@app/hooks/api";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
// Tooltip,
// IconButton,
// EmptyState,
Table,
TableContainer,
// TableSkeleton,
TBody,
Td,
Th,
THead,
Tr} from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context";
// import { UsePopUpState } from "@app/hooks/usePopUp";
formRolePermission2API,
formSchema,
rolePermission2Form,
TFormSchema
} from "@app/views/Org/MembersPage/components/OrgRoleTabSection/OrgRoleModifySection/OrgRoleModifySection.utils";
// import { IdentityProjectRow } from "./IdentityProjectRow";
import { RolePermissionRow } from "./RolePermissionRow";
// type Props = {
// identityId: string;
// handlePopUpOpen: (
// popUpName: keyof UsePopUpState<["removeIdentityFromProject"]>,
// data?: {}
// ) => 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;
type Props = {
roleId: string;
};
export const RolePermissionsTable = ({ roleId }: Props) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
const { data: role } = useGetOrgRole(orgId, roleId);
const { setValue, control, handleSubmit } = useForm<TFormSchema>({
defaultValues: role ? { ...role, permissions: rolePermission2Form(role.permissions) } : {},
resolver: zodResolver(formSchema)
});
const { mutateAsync: updateRole } = useUpdateOrgRole();
const onSubmit = async (el: TFormSchema) => {
try {
await updateRole({
orgId,
id: roleId,
...el,
permissions: formRolePermission2API(el.permissions)
});
createNotification({ type: "success", text: "Successfully updated role" });
} catch (err) {
console.log(err);
createNotification({ type: "error", text: "Failed to update role" });
}
};
export const RolePermissionsTable = () => {
// const { data: projectMemberships, isLoading } = useGetIdentityProjectMemberships(identityId);
return (
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Resource</Th>
<Th>Allowed Actions</Th>
<Th className="w-5" />
</Tr>
</THead>
<TBody>
<Tr>
<Td>Identity</Td>
<Td>Create/Read</Td>
<Td>
<DropdownMenu>
<DropdownMenuTrigger asChild className="rounded-lg">
<div className="hover:text-primary-400 data-[state=open]:text-primary-400">
<FontAwesomeIcon size="sm" icon={faEllipsis} />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="p-1">
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Role}>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
!isAllowed && "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
// TODO
}}
disabled={!isAllowed}
>
Edit Permission
</DropdownMenuItem>
)}
</OrgPermissionCan>
<OrgPermissionCan
I={OrgPermissionActions.Edit}
a={OrgPermissionSubjects.Identity}
>
{(isAllowed) => (
<DropdownMenuItem
className={twMerge(
isAllowed
? "hover:!bg-red-500 hover:!text-white"
: "pointer-events-none cursor-not-allowed opacity-50"
)}
onClick={(e) => {
e.stopPropagation();
// handlePopUpOpen("deleteIdentity", {
// identityId: id,
// name
// });
}}
disabled={!isAllowed}
>
Delete Permission
</DropdownMenuItem>
)}
</OrgPermissionCan>
</DropdownMenuContent>
</DropdownMenu>
</Td>
</Tr>
{/* <TableSkeleton columns={3} innerKey="role-permissions" /> */}
{/* {isLoading && <TableSkeleton columns={2} innerKey="identity-project-memberships" />} */}
{/* {!isLoading &&
projectMemberships?.map((membership) => {
<form onSubmit={handleSubmit(onSubmit)}>
<Table>
<THead>
<Tr>
<Th className="w-5" />
<Th>Resource</Th>
<Th>Permission</Th>
</Tr>
</THead>
<TBody>
{SIMPLE_PERMISSION_OPTIONS.map((permission) => {
return (
<div key={`membership-${membership.id}`}>Row</div>
<IdentityProjectRow
key={`identity-project-membership-${membership.id}`}
membership={membership}
handlePopUpOpen={handlePopUpOpen}
<RolePermissionRow
title={permission.title}
formName={permission.formName}
control={control}
setValue={setValue}
handleSubmit={handleSubmit(onSubmit)}
key={`org-role-${roleId}-permission-${permission.formName}`}
/>
);
})} */}
</TBody>
</Table>
{/* <EmptyState title="This role does not have any permissions on it" icon={faShield} /> */}
{/* {!isLoading && !projectMemberships?.length && (
<EmptyState title="This identity has not been assigned to any projects" icon={faKey} />
)} */}
})}
</TBody>
</Table>
</form>
</TableContainer>
);
};
@@ -1,103 +0,0 @@
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>
);
};