diff --git a/src/utils/permissions.ts b/src/utils/permissions.ts index 6108278..ca1ae2d 100755 --- a/src/utils/permissions.ts +++ b/src/utils/permissions.ts @@ -1,8 +1,33 @@ +import { useMemo } from 'react' + import { getUserPermissions, getUserRoles } from './storage' export type Role = string export type Permission = string +export type ServiceName = string +export type ServiceRequestType = 'get' | 'edit' | 'delete' +export type PermissionRequest = `${ServiceName}.${ServiceRequestType}` + +export function isRequestType(value: string): value is ServiceRequestType { + return ['get', 'edit', 'delete'].includes(value) +} + +export const usePermissions = (...values: PermissionRequest[]) => { + const result = useMemo(() => { + const permissions: Record>> = {} + values.forEach((key) => { + const [service, type] = key.toLowerCase().split('.') + if (!isRequestType(type)) return + permissions[service] = permissions[service] ?? {} + permissions[service][type] = hasPermission(key) + }) + return permissions + }, [values]) + + return result +} + export const hasPermission = (permission?: Permission | Permission[], userPermissions?: Permission[]): boolean => { if (!Array.isArray(permission) && typeof permission !== 'string') return true