51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import { useContext, useEffect } from "react";
|
|
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
|
|
import GlobalStateContext from "./Contexts/GlobalStateContext";
|
|
import DefaultLayout from "./Layouts/DefaultLayout";
|
|
import Login from "./Pages/Login";
|
|
import { RouteLink } from "./Routes/Routes";
|
|
|
|
function App() {
|
|
const context = useContext(GlobalStateContext);
|
|
if (!context) throw new Error("App must be used within a GlobalStateProvider");
|
|
|
|
const { isAuthenticate, setIsAuthenticate } = context;
|
|
|
|
useEffect(() => {
|
|
const token = localStorage.getItem("token");
|
|
setIsAuthenticate(!!token); // Converts token to boolean
|
|
}, [setIsAuthenticate]);
|
|
|
|
console.log("Auth Status:", isAuthenticate);
|
|
|
|
return (
|
|
<Router>
|
|
<Routes>
|
|
{/* Redirect logged-in users away from login */}
|
|
<Route path="/login" element={isAuthenticate && localStorage.getItem("token") ? <Navigate to="/" /> : <Login />} />
|
|
|
|
{/* Protected Routes */}
|
|
<Route
|
|
path="/*"
|
|
element={isAuthenticate && localStorage.getItem("token") ? (
|
|
<DefaultLayout>
|
|
<Routes>
|
|
{RouteLink.map(({ path, Component }, index) => (
|
|
<Route key={index} path={path} element={<Component />} />
|
|
))}
|
|
</Routes>
|
|
</DefaultLayout>
|
|
) : (
|
|
<Navigate to="/login" />
|
|
)}
|
|
/>
|
|
|
|
{/* Catch-all route to prevent unauthorized access */}
|
|
<Route path="*" element={<Navigate to="/login" />} />
|
|
</Routes>
|
|
</Router>
|
|
);
|
|
}
|
|
|
|
export default App;
|