Add basic permissions checking logic to frontend

This commit is contained in:
Dane Everitt 2020-03-28 17:25:04 -07:00
parent 7e0ac2c311
commit ab4c4e7e9e
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
4 changed files with 81 additions and 11 deletions

View file

@ -0,0 +1,44 @@
import React, { useMemo } from 'react';
import { ServerContext } from '@/state/server';
interface Props {
action: string | string[];
renderOnError?: React.ReactNode | null;
children: React.ReactNode;
}
const Can = ({ action, renderOnError, children }: Props) => {
const userPermissions = ServerContext.useStoreState(state => state.server.permissions);
const actions = Array.isArray(action) ? action : [ action ];
const missingPermissionCount = useMemo(() => {
if (userPermissions[0] === '*') {
return 0;
}
return actions.filter(permission => {
return !(
// Allows checking for any permission matching a name, for example files.*
// will return if the user has any permission under the file.XYZ namespace.
(
permission.endsWith('.*')
&& permission !== 'websocket.*'
&& userPermissions.filter(p => p.startsWith(permission.split('.')[0])).length > 0
)
// Otherwise just check if the entire permission exists in the array or not.
|| userPermissions.indexOf(permission) >= 0);
}).length;
}, [ action, userPermissions ]);
return (
<>
{missingPermissionCount > 0 ?
renderOnError
:
children
}
</>
);
};
export default Can;