mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
import React from 'react';
|
|
import { Navigate } from 'react-router-dom';
|
|
import { usePermissions } from '@/hooks/usePermissions';
|
|
import { Permission } from '@/types/permissions';
|
|
import { Alert } from '@/components/ui';
|
|
|
|
export interface RequirePermissionProps {
|
|
children: React.ReactNode;
|
|
permission: Permission | Permission[];
|
|
requireAll?: boolean;
|
|
fallback?: React.ReactNode;
|
|
showError?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Component that renders children only if user has required permission(s)
|
|
*/
|
|
export const RequirePermission = ({
|
|
children,
|
|
permission,
|
|
requireAll = false,
|
|
fallback,
|
|
showError = false,
|
|
}: RequirePermissionProps) => {
|
|
const { checkPermission, checkAnyPermission, checkAllPermissions } = usePermissions();
|
|
|
|
const permissions = Array.isArray(permission) ? permission : [permission];
|
|
const hasAccess = requireAll ? checkAllPermissions(permissions) : checkAnyPermission(permissions);
|
|
|
|
if (!hasAccess) {
|
|
if (showError) {
|
|
return (
|
|
<Alert
|
|
variant="error"
|
|
title="Access Denied"
|
|
description="You don't have permission to access this content."
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (fallback) {
|
|
return <>{fallback}</>;
|
|
}
|
|
|
|
return <Navigate to="/" replace />;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
};
|