36 lines
1001 B
TypeScript
Executable File
36 lines
1001 B
TypeScript
Executable File
import { ReactNode } from 'react';
|
|
import { Container, Alert, AlertTitle } from '@mui/material';
|
|
import useAuth from '@/hooks/useAuth';
|
|
import Page404 from '@/pages/Page404';
|
|
|
|
// ----------------------------------------------------------------------
|
|
|
|
type RoleBasedGuardProp = {
|
|
accessibleRoles: string[];
|
|
children: ReactNode | string;
|
|
};
|
|
|
|
const useCurrentRole = () => {
|
|
// Fetch the role from useAuth
|
|
const { user } = useAuth();
|
|
const formattedRoleName = user?.role.name || ''; // Default to empty string if role is undefined
|
|
return formattedRoleName;
|
|
};
|
|
|
|
export default function RoleBasedGuard({ accessibleRoles, children }: RoleBasedGuardProp) {
|
|
const currentRole = useCurrentRole();
|
|
|
|
if (!accessibleRoles.includes(currentRole)) {
|
|
return (
|
|
<Container>
|
|
<Alert severity="error">
|
|
<AlertTitle>Permission Denied</AlertTitle>
|
|
You do not have permission to access this page
|
|
</Alert>
|
|
</Container>
|
|
);
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|