turash/bugulma/frontend/components/auth/RequirePermission.tsx
2025-12-15 10:06:41 +01:00

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}</>;
};