2021-10-08 11:23:29 +02:00
|
|
|
import { Button, Tooltip } from '@material-ui/core';
|
|
|
|
import { Lock } from '@material-ui/icons';
|
2022-02-25 10:55:39 +01:00
|
|
|
import React, { useContext } from 'react';
|
2021-10-08 11:23:29 +02:00
|
|
|
import AccessContext from '../../../contexts/AccessContext';
|
|
|
|
import ConditionallyRender from '../ConditionallyRender';
|
|
|
|
|
2022-01-26 10:58:35 +01:00
|
|
|
export interface IPermissionIconButtonProps
|
2022-01-14 15:50:02 +01:00
|
|
|
extends React.HTMLProps<HTMLButtonElement> {
|
|
|
|
permission: string | string[];
|
|
|
|
tooltip?: string;
|
2021-10-08 11:23:29 +02:00
|
|
|
onClick?: (e: any) => void;
|
|
|
|
disabled?: boolean;
|
2021-10-20 12:05:44 +02:00
|
|
|
projectId?: string;
|
2022-01-14 15:50:02 +01:00
|
|
|
environmentId?: string;
|
2021-10-08 11:23:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const PermissionButton: React.FC<IPermissionIconButtonProps> = ({
|
|
|
|
permission,
|
2022-02-23 13:45:37 +01:00
|
|
|
tooltip,
|
2021-10-08 11:23:29 +02:00
|
|
|
onClick,
|
|
|
|
children,
|
|
|
|
disabled,
|
2021-10-20 12:05:44 +02:00
|
|
|
projectId,
|
2022-01-14 15:50:02 +01:00
|
|
|
environmentId,
|
2021-10-08 11:23:29 +02:00
|
|
|
...rest
|
|
|
|
}) => {
|
|
|
|
const { hasAccess } = useContext(AccessContext);
|
2022-01-14 15:50:02 +01:00
|
|
|
let access;
|
2021-10-08 11:23:29 +02:00
|
|
|
|
2022-01-14 15:50:02 +01:00
|
|
|
const handleAccess = () => {
|
|
|
|
let access;
|
|
|
|
if (Array.isArray(permission)) {
|
|
|
|
access = permission.some(permission => {
|
|
|
|
if (projectId && environmentId) {
|
|
|
|
return hasAccess(permission, projectId, environmentId);
|
|
|
|
} else if (projectId) {
|
|
|
|
return hasAccess(permission, projectId);
|
|
|
|
} else {
|
|
|
|
return hasAccess(permission);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
if (projectId && environmentId) {
|
|
|
|
access = hasAccess(permission, projectId, environmentId);
|
|
|
|
} else if (projectId) {
|
|
|
|
access = hasAccess(permission, projectId);
|
|
|
|
} else {
|
|
|
|
access = hasAccess(permission);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return access;
|
|
|
|
};
|
|
|
|
|
|
|
|
access = handleAccess();
|
2021-10-20 12:05:44 +02:00
|
|
|
|
2022-02-23 13:45:37 +01:00
|
|
|
const tooltipText = !access
|
|
|
|
? "You don't have access to perform this operation"
|
|
|
|
: '';
|
2021-10-08 11:23:29 +02:00
|
|
|
|
|
|
|
return (
|
|
|
|
<Tooltip title={tooltipText} arrow>
|
|
|
|
<span>
|
|
|
|
<Button
|
|
|
|
onClick={onClick}
|
|
|
|
disabled={disabled || !access}
|
|
|
|
variant="contained"
|
|
|
|
color="primary"
|
|
|
|
{...rest}
|
|
|
|
endIcon={
|
|
|
|
<ConditionallyRender
|
|
|
|
condition={!access}
|
|
|
|
show={<Lock />}
|
|
|
|
/>
|
|
|
|
}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</Button>
|
|
|
|
</span>
|
|
|
|
</Tooltip>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default PermissionButton;
|