Here is the protected route where I have checked for isAuthenticated
. The isAuthenticated
status is managed by Redux. When there is no token saved in local storage, isAuthenticated
is set to false. This is for protective routes:
import PropTypes from "prop-types";
import { useEffect } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { RootState } from "src/store";
const ProtectedRoute = ({ children }) => {
const navigate = useNavigate();
const { isAuthenticated } = useSelector((state: RootState) => state.login);
useEffect(() => {
if (!isAuthenticated) {
navigate("/");
}
}, [isAuthenticated]);
return children;
};
ProtectedRoute.propTypes = {
children: PropTypes.node.isRequired,
};
export default ProtectedRoute;
Logic to check user permission:
import { ReactNode, Fragment } from "react";
import { Navigate } from "react-router-dom";
import { useUserRoles } from "src/utils/ToastMessage";
interface RolesAuthRouteProps {
children: ReactNode;
roles: Array<string>;
}
export function RolesAuthRoute({ children, roles }: RolesAuthRouteProps) {
const userRoles = useUserRoles();
const canAccess = userRoles.some(userRole => roles.includes(userRole));
if (canAccess) return <>{children}</>;
return <Navigate to="/" />;
}
Logic to check unprotected route:
import { useSelector } from "react-redux";
import { Navigate, Outlet } from "react-router-dom";
import { RootState } from "src/store";
const UnProtectedRoute = () => {
const { isAuthenticated } = useSelector((state: RootState) => state.login);
return isAuthenticated ? <Navigate to="/dashboard" replace /> : <Outlet />;
};
export default UnProtectedRoute;
Here I have defined all routes:
<BrowserRouter>
<Routes>
<Route element={<UnProtectedRoute />}>
<Route element={<Login />} path="/" />
</Route>
<Route
path="dashboard"
element={
<ProtectedRoute>
<RolesAuthRoute roles={["admin"]}>
<Dashboard />
</RolesAuthRoute>
</ProtectedRoute>
}
/>
<Route
path="reports"
element={
<ProtectedRoute>
<RolesAuthRoute roles={["admin"]}>
<DashboardDetails />
</RolesAuthRoute>
</ProtectedRoute>
}
/>
</Routes>
</BrowserRouter>
When I attempt to navigate to reports, only dashboard links are rendered. I am unable to access other protected routes.