56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
'use client';
|
|
|
|
import { useMemo } from 'react';
|
|
|
|
import { useAppStore } from '@/store/app.store';
|
|
|
|
export type PermissionInput = string | undefined;
|
|
|
|
export function hasPermissionValue({
|
|
grantedPermissions,
|
|
permissions,
|
|
}: {
|
|
grantedPermissions: string[];
|
|
permissions: PermissionInput;
|
|
}) {
|
|
if (!permissions) return true;
|
|
|
|
const normalizedPermissions = new Set(
|
|
grantedPermissions.map((permission) => permission.toLowerCase()),
|
|
);
|
|
|
|
return normalizedPermissions.has(permissions.toLowerCase());
|
|
}
|
|
|
|
function hasAnyPermissionValue({
|
|
grantedPermissions,
|
|
permissions,
|
|
}: {
|
|
grantedPermissions: string[];
|
|
permissions: PermissionInput[];
|
|
}) {
|
|
if (permissions.length === 0) return true;
|
|
|
|
return permissions.some((permission) =>
|
|
hasPermissionValue({ grantedPermissions, permissions: permission }),
|
|
);
|
|
}
|
|
|
|
export function usePermissions() {
|
|
const grantedPermissions = useAppStore((state) => state.permissions);
|
|
|
|
return useMemo(
|
|
() => ({
|
|
grantedPermissions,
|
|
hasPermission: (permissions: PermissionInput) =>
|
|
hasPermissionValue({
|
|
grantedPermissions,
|
|
permissions,
|
|
}),
|
|
hasAnyPermission: (permissions: PermissionInput[]) =>
|
|
hasAnyPermissionValue({ grantedPermissions, permissions }),
|
|
}),
|
|
[grantedPermissions],
|
|
);
|
|
}
|