Files
sam-react-prod/src/hooks/usePermission.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

'use client';
import { usePathname } from 'next/navigation';
import { usePermissionContext } from '@/contexts/PermissionContext';
import { findMatchingUrl } from '@/lib/permissions/utils';
import { ALL_ALLOWED } from '@/lib/permissions/types';
import type { UsePermissionReturn } from '@/lib/permissions/types';
/**
* URL
*
* URL .
* URL .
*
* @example
* // 자동 매칭 (대부분의 경우)
* const { canView, canCreate, canUpdate, canDelete } = usePermission();
*
* // URL 직접 지정 (다른 메뉴 권한 체크 시)
* const { canApprove } = usePermission('/approval/inbox');
*/
export function usePermission(overrideUrl?: string): UsePermissionReturn {
const pathname = usePathname();
const { permissionMap, isLoading } = usePermissionContext();
const targetPath = overrideUrl || pathname;
if (isLoading || !permissionMap) {
return { ...ALL_ALLOWED, isLoading };
}
const matchedUrl = findMatchingUrl(targetPath, permissionMap);
if (!matchedUrl) {
return ALL_ALLOWED;
}
const perms = permissionMap[matchedUrl] || {};
return {
canView: perms.view ?? true,
canCreate: perms.create ?? true,
canUpdate: perms.update ?? true,
canDelete: perms.delete ?? true,
canApprove: perms.approve ?? true,
canExport: perms.export ?? true,
isLoading: false,
matchedUrl,
};
}