Update permissions checking code

This commit is contained in:
Dane Everitt 2020-03-29 14:19:17 -07:00
parent 2e9d327dfc
commit 8bc81c8c4b
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
7 changed files with 79 additions and 43 deletions

View file

@ -1,5 +1,5 @@
import React, { useMemo } from 'react';
import { ServerContext } from '@/state/server';
import React from 'react';
import { usePermissions } from '@/plugins/usePermissions';
interface Props {
action: string | string[];
@ -8,35 +8,11 @@ interface Props {
}
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 ]);
const can = usePermissions(action);
return (
<>
{missingPermissionCount > 0 ?
renderOnError
:
children
}
{can.every(p => p) ? children : renderOnError}
</>
);
};