From 5d5a5c2afc7e067f3b2630c97d6cb2dd504ddf4b Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sun, 29 Mar 2020 21:52:18 -0700 Subject: [PATCH] Fix array fill logicl; allow matching on any permissions --- resources/scripts/components/elements/Can.tsx | 14 ++++++++++++-- resources/scripts/plugins/usePermissions.ts | 4 +--- resources/scripts/routers/ServerRouter.tsx | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/resources/scripts/components/elements/Can.tsx b/resources/scripts/components/elements/Can.tsx index ee6393719..2990f2489 100644 --- a/resources/scripts/components/elements/Can.tsx +++ b/resources/scripts/components/elements/Can.tsx @@ -3,16 +3,26 @@ import { usePermissions } from '@/plugins/usePermissions'; interface Props { action: string | string[]; + matchAny?: boolean; renderOnError?: React.ReactNode | null; children: React.ReactNode; } -const Can = ({ action, renderOnError, children }: Props) => { +const Can = ({ action, matchAny = false, renderOnError, children }: Props) => { const can = usePermissions(action); + if (matchAny) { + console.log('Can.tsx', can); + } + return ( <> - {can.every(p => p) ? children : renderOnError} + { + ((matchAny && can.filter(p => p).length > 0) || (!matchAny && can.every(p => p))) ? + children + : + renderOnError + } ); }; diff --git a/resources/scripts/plugins/usePermissions.ts b/resources/scripts/plugins/usePermissions.ts index 974e09434..89dbd64bc 100644 --- a/resources/scripts/plugins/usePermissions.ts +++ b/resources/scripts/plugins/usePermissions.ts @@ -6,9 +6,7 @@ export const usePermissions = (action: string | string[]): boolean[] => { return useDeepMemo(() => { if (userPermissions[0] === '*') { - return ([] as boolean[]).fill( - true, 0, Array.isArray(action) ? action.length : 1, - ); + return Array(Array.isArray(action) ? action.length : 1).fill(true); } return (Array.isArray(action) ? action : [ action ]) diff --git a/resources/scripts/routers/ServerRouter.tsx b/resources/scripts/routers/ServerRouter.tsx index ff7fe73ec..241337b79 100644 --- a/resources/scripts/routers/ServerRouter.tsx +++ b/resources/scripts/routers/ServerRouter.tsx @@ -47,7 +47,7 @@ const ServerRouter = ({ match, location }: RouteComponentProps<{ id: string }>) Users - + Settings