1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-09-15 17:50:48 +02:00
unleash.unleash/frontend/src/component/common/PermissionGuard/PermissionGuard.tsx
Nuno Góis 4167a60588
feat: biome lint frontend (#4903)
Follows up on https://github.com/Unleash/unleash/pull/4853 to add Biome
to the frontend as well.


![image](https://github.com/Unleash/unleash/assets/14320932/1906faf1-fc29-4172-a4d4-b2716d72cd65)

Added a few `biome-ignore` to speed up the process but we may want to
check and fix them in the future.
2023-10-02 13:25:46 +01:00

55 lines
1.4 KiB
TypeScript

import { useContext } from 'react';
import { Alert, styled } from '@mui/material';
import { ADMIN } from '@server/types/permissions';
import AccessContext from 'contexts/AccessContext';
const StyledList = styled('ul')(({ theme }) => ({
paddingInlineStart: theme.spacing(2),
}));
interface IPermissionGuardProps {
permissions: string | string[];
children: JSX.Element;
}
export const PermissionGuard = ({
permissions,
children,
}: IPermissionGuardProps) => {
const { hasAccess } = useContext(AccessContext);
const permissionsArray = Array.isArray(permissions)
? permissions
: [permissions];
if (!permissionsArray.includes(ADMIN)) {
permissionsArray.push(ADMIN);
}
if (hasAccess(permissionsArray)) {
return children;
}
if (permissionsArray.length === 1) {
return (
<Alert severity='error'>
You need the <strong>{permissionsArray[0]}</strong> permission
to access this section.
</Alert>
);
}
return (
<Alert severity='error'>
You need one of the following permissions to access this section:
<StyledList>
{permissionsArray.sort().map((permission) => (
<li key={permission}>
<strong>{permission}</strong>
</li>
))}
</StyledList>
</Alert>
);
};