Update permissions checking code
This commit is contained in:
parent
2e9d327dfc
commit
8bc81c8c4b
7 changed files with 79 additions and 43 deletions
12
resources/scripts/plugins/useDeepMemo.ts
Normal file
12
resources/scripts/plugins/useDeepMemo.ts
Normal file
|
@ -0,0 +1,12 @@
|
|||
import { useRef } from 'react';
|
||||
import isEqual from 'lodash-es/isEqual';
|
||||
|
||||
export const useDeepMemo = <T, K> (fn: () => T, key: K): T => {
|
||||
const ref = useRef<{ key: K, value: T }>();
|
||||
|
||||
if (!ref.current || !isEqual(key, ref.current.key)) {
|
||||
ref.current = { key, value: fn() };
|
||||
}
|
||||
|
||||
return ref.current.value;
|
||||
};
|
22
resources/scripts/plugins/usePermissions.ts
Normal file
22
resources/scripts/plugins/usePermissions.ts
Normal file
|
@ -0,0 +1,22 @@
|
|||
import { ServerContext } from '@/state/server';
|
||||
import { useDeepMemo } from '@/plugins/useDeepMemo';
|
||||
|
||||
export const usePermissions = (action: string | string[]): boolean[] => {
|
||||
const userPermissions = ServerContext.useStoreState(state => state.server.permissions);
|
||||
|
||||
return useDeepMemo(() => {
|
||||
return (Array.isArray(action) ? action : [ action ])
|
||||
.map(permission => (
|
||||
// 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
|
||||
),
|
||||
);
|
||||
}, [ action, userPermissions ]);
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue