2020-03-29 21:19:17 +00:00
|
|
|
import { ServerContext } from '@/state/server';
|
2020-08-26 04:25:31 +00:00
|
|
|
import { useDeepCompareMemo } from '@/plugins/useDeepCompareMemo';
|
2020-03-29 21:19:17 +00:00
|
|
|
|
|
|
|
export const usePermissions = (action: string | string[]): boolean[] => {
|
2022-06-26 19:13:52 +00:00
|
|
|
const userPermissions = ServerContext.useStoreState((state) => state.server.permissions);
|
2020-03-29 21:19:17 +00:00
|
|
|
|
2020-08-26 04:25:31 +00:00
|
|
|
return useDeepCompareMemo(() => {
|
2020-03-30 04:30:33 +00:00
|
|
|
if (userPermissions[0] === '*') {
|
2020-03-30 04:52:18 +00:00
|
|
|
return Array(Array.isArray(action) ? action.length : 1).fill(true);
|
2020-03-30 04:30:33 +00:00
|
|
|
}
|
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
return (Array.isArray(action) ? action : [action]).map(
|
|
|
|
(permission) =>
|
2020-03-30 04:30:33 +00:00
|
|
|
// Allows checking for any permission matching a name, for example files.*
|
|
|
|
// will return if the user has any permission under the file.XYZ namespace.
|
2022-06-26 19:13:52 +00:00
|
|
|
(permission.endsWith('.*') &&
|
|
|
|
userPermissions.filter((p) => p.startsWith(permission.split('.')[0])).length > 0) ||
|
2020-03-30 04:30:33 +00:00
|
|
|
// Otherwise just check if the entire permission exists in the array or not.
|
|
|
|
userPermissions.indexOf(permission) >= 0
|
2022-06-26 19:13:52 +00:00
|
|
|
);
|
|
|
|
}, [action, userPermissions]);
|
2020-03-29 21:19:17 +00:00
|
|
|
};
|