mirror of
https://github.com/Unleash/unleash.git
synced 2025-09-24 17:51:14 +02:00
I noticed some manual `hasAccess` usages in permission guards due to the fact that `PermissionGuard` does not accept `project` and `environment`. This PR adds this support to `PermissionGuard` so we can adapt these `hasAccess` checks to use it instead, adding consistency and cleaning things up. This PR does not include these adaptations however, it only adds the optional properties to the component. We can address these at a later point.
59 lines
1.5 KiB
TypeScript
59 lines
1.5 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[];
|
|
project?: string;
|
|
environment?: string;
|
|
children: JSX.Element;
|
|
}
|
|
|
|
export const PermissionGuard = ({
|
|
permissions,
|
|
project,
|
|
environment,
|
|
children,
|
|
}: IPermissionGuardProps) => {
|
|
const { hasAccess } = useContext(AccessContext);
|
|
|
|
const permissionsArray = Array.isArray(permissions)
|
|
? permissions
|
|
: [permissions];
|
|
|
|
if (!permissionsArray.includes(ADMIN)) {
|
|
permissionsArray.push(ADMIN);
|
|
}
|
|
|
|
if (hasAccess(permissionsArray, project, environment)) {
|
|
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>
|
|
);
|
|
};
|