mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-26 19:12:50 +00:00
- Added RequirePermission component to manage access based on user permissions. - Integrated permission checks in MySeaRecordsPage, SeafarerRegistrationPage, VesselRegistrationPage, WaiverPage, and PortalLayout. - Updated router to enforce permissions for specific routes. - Introduced PORTAL_PERMISSIONS and LICENSE_PERMISSIONS constants for consistent permission management. - Enhanced usePermissions hook to fetch permissions from the server and determine access rights. - Refactored UI components to conditionally render based on user permissions, improving security and user experience.
40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import type { ReactNode } from 'react';
|
|
import { Navigate } from 'react-router-dom';
|
|
import { usePermissions } from '../hooks/usePermissions';
|
|
|
|
interface RequirePermissionProps {
|
|
/** Passes when the user holds ANY of these keys. */
|
|
anyOf: string[];
|
|
/** Route mode: where to send a denied user. Defaults to "/". */
|
|
redirectTo?: string;
|
|
/**
|
|
* Element mode: render nothing instead of redirecting. Use for buttons and
|
|
* page fragments; leave false for route elements.
|
|
*/
|
|
hideOnly?: boolean;
|
|
children: ReactNode;
|
|
}
|
|
|
|
/**
|
|
* Permission gate for routes, sections and buttons.
|
|
*
|
|
* Route usage: <Route element={<RequirePermission anyOf={[KEY]}><Page /></RequirePermission>} />
|
|
* Element usage: <RequirePermission anyOf={[KEY]} hideOnly><Button /></RequirePermission>
|
|
*
|
|
* While the permission list is still loading (`known === false`) it renders
|
|
* children — the API enforces the real rule, and a flash of a forbidden
|
|
* button costs at most a 403, whereas hiding everything flashes an empty app
|
|
* at every legitimate user on every load.
|
|
*/
|
|
export function RequirePermission({
|
|
anyOf,
|
|
redirectTo = '/',
|
|
hideOnly = false,
|
|
children,
|
|
}: RequirePermissionProps) {
|
|
const { can, known } = usePermissions();
|
|
|
|
if (!known || can(anyOf)) return <>{children}</>;
|
|
return hideOnly ? null : <Navigate to={redirectTo} replace />;
|
|
}
|