Skip to content

Commit

Permalink
Add protected route
Browse files Browse the repository at this point in the history
  • Loading branch information
jonashonecker committed Jun 19, 2024
1 parent fb6ff9c commit 440330c
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 1 deletion.
91 changes: 91 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@fontsource/roboto": "^5.0.13",
"@mui/icons-material": "^5.15.20",
"@mui/material": "^5.15.20",
"axios": "^1.7.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1"
Expand Down
24 changes: 23 additions & 1 deletion frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,35 @@ import CssBaseline from "@mui/material/CssBaseline";
import LoginPage from "./components/LoginPage.tsx";
import { Route, Routes } from "react-router-dom";
import MainPage from "./components/MainPage.tsx";
import { useEffect, useState } from "react";
import axios from "axios";
import ProtectedRoute from "./components/ProtectedRoute.tsx";

export default function App() {
const [user, setUser] = useState<string | null | undefined>(undefined);

const loadUser = () => {
axios
.get("/api/auth/me")
.then((response) => {
setUser(response.data);
})
.catch(() => {
setUser(null);
});
};

useEffect(() => {
loadUser();
}, []);

return (
<React.Fragment>
<CssBaseline />
<Routes>
<Route path="/" element={<MainPage />} />
<Route element={<ProtectedRoute user={user} />}>
<Route path="/" element={<MainPage />} />
</Route>
<Route path="/login" element={<LoginPage />} />
</Routes>
</React.Fragment>
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/components/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Navigate, Outlet } from "react-router-dom";

type ProtectedRouteProps = {
user: string | undefined | null;
};

export default function ProtectedRoute({ user }: ProtectedRouteProps) {
if (user === undefined) {
return <div>Loading...</div>;
}

return user ? <Outlet /> : <Navigate to="/login" />;
}

0 comments on commit 440330c

Please sign in to comment.