From fa8e2d234dbbcd5016200d262ba0445c9b91c0c2 Mon Sep 17 00:00:00 2001 From: goodmice Date: Tue, 31 May 2022 17:18:23 +0500 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D1=85=D1=83=D0=BA=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=80=D0=B0=D0=B7=D1=80=D0=B5=D1=88?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/permissions.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) 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