misc_pterodactyl-panel/resources/scripts/plugins/usePermissions.ts

23 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2020-03-29 21:19:17 +00:00
import { ServerContext } from '@/state/server';
import { useDeepCompareMemo } from '@/plugins/useDeepCompareMemo';
2020-03-29 21:19:17 +00:00
export const usePermissions = (action: string | string[]): boolean[] => {
2022-11-25 20:25:03 +00:00
const userPermissions = ServerContext.useStoreState(state => state.server.permissions);
2020-03-29 21:19:17 +00:00
return useDeepCompareMemo(() => {
if (userPermissions[0] === '*') {
return Array(Array.isArray(action) ? action.length : 1).fill(true);
}
return (Array.isArray(action) ? action : [action]).map(
2022-11-25 20:25:03 +00:00
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('.*') &&
2022-11-25 20:25:03 +00:00
userPermissions.filter(p => p.startsWith(permission.split('.')?.[0] ?? '')).length > 0) ||
// Otherwise just check if the entire permission exists in the array or not.
2022-11-25 20:25:03 +00:00
userPermissions.indexOf(permission) >= 0,
);
}, [action, userPermissions]);
2020-03-29 21:19:17 +00:00
};