'use client'; /** * @file PermissionGuard.tsx * @description Role-Based Access Control (RBAC) HOC/Wrapper component. * Only renders children if the user's role is in the allowedRoles list. * Use this to protect any UI element that requires authorization. * * @example * // Only admins and editors can see the edit button * * * */ import React from 'react'; import { PermissionGuardProps, UserRole } from '@/types/publications'; /** Priority order of roles (higher index = more permissions) */ const ROLE_HIERARCHY: Record = { guest: 0, viewer: 1, editor: 2, admin: 3, }; /** * Checks if a given role meets the minimum required role. */ export function hasPermission(userRole: UserRole, allowedRoles: UserRole[]): boolean { return allowedRoles.some( (allowed) => ROLE_HIERARCHY[userRole] >= ROLE_HIERARCHY[allowed] ); } /** * PermissionGuard — Renders children only if userRole is in allowedRoles. * Renders `fallback` (or null) otherwise. */ export const PermissionGuard: React.FC = ({ allowedRoles, userRole, children, fallback = null, }) => { if (!hasPermission(userRole, allowedRoles)) { return <>{fallback}; } return <>{children}; }; export default PermissionGuard;