import type { ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
interface PermissionGuardProps {
children: ReactNode
permission?: string
permissions?: string[]
requireAll?: boolean
fallback?: ReactNode
}
/**
* Guard component that checks user permissions before rendering children.
*
* Usage:
*
*
*
*
*
*
*
*/
export default function PermissionGuard({
children,
permission,
permissions,
requireAll = false,
fallback,
}: PermissionGuardProps) {
const { user, loading, hasPermission, hasAnyPermission } = useAuth()
if (loading) {
return
Загрузка...
}
if (!user) {
return
}
// Check single permission
if (permission && !hasPermission(permission)) {
if (fallback) return <>{fallback}>
return (
403
Нет прав доступа
Требуется: {permission}
)
}
// Check multiple permissions
if (permissions && permissions.length > 0) {
const hasAccess = requireAll
? permissions.every(p => hasPermission(p))
: hasAnyPermission(permissions)
if (!hasAccess) {
if (fallback) return <>{fallback}>
return (
403
Нет прав доступа
Требуется: {permissions.join(requireAll ? ' + ' : ' или ')}
)
}
}
return <>{children}>
}