Skip to content

Commit cddcfcc

Browse files
committed
update
1 parent 98f12d0 commit cddcfcc

2 files changed

Lines changed: 50 additions & 2 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import React, { useEffect } from "react";
2+
import { Navigate, useLocation } from "react-router-dom";
3+
import { getCookie } from "../utils/CookieService";
4+
import { toast } from "sonner";
5+
6+
export default function ProtectedRoute({ children, routeType }) {
7+
const location = useLocation();
8+
const admin_uid = getCookie("admin_uid");
9+
10+
const isAdmin = !!admin_uid;
11+
12+
useEffect(() => {
13+
if (!isAdmin && (routeType === "admin")) {
14+
toast("This page is restricted to admins only");
15+
}
16+
}, [routeType, isAdmin]);
17+
18+
if (routeType === "login" && isAdmin) {
19+
return <Navigate to="/admin" replace />;
20+
}
21+
22+
if (routeType === "admin" && !isAdmin) {
23+
return <Navigate to="/" state={{ from: location }} replace />;
24+
}
25+
26+
return children;
27+
}

frontend_tailwind/src/app/routes.jsx

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,32 @@ import AdminSheets from "@/pages/Admin/Sheets/Sheets";
1111
import AddBranch from "@/pages/Admin/AddBranch/AddBranch";
1212
import { AuthProvider } from "@/contexts/AuthContext";
1313
import { ApiProvider } from "@/contexts/ApiContext";
14+
import ProtectedRoute from "./ProtectedRoute"; // 👈 import it
1415

1516
export default function AppRoutes() {
1617
return (
1718
<AuthProvider>
1819
<ApiProvider>
1920
<Routes>
20-
<Route path="*" element={<Login />} />
21-
<Route path="/admin" element={<SidebarDemo />}>
21+
{/* Login route */}
22+
<Route
23+
path="/"
24+
element={
25+
<ProtectedRoute routeType="login">
26+
<Login />
27+
</ProtectedRoute>
28+
}
29+
/>
30+
31+
{/* All /admin routes protected */}
32+
<Route
33+
path="/admin"
34+
element={
35+
<ProtectedRoute routeType="admin">
36+
<SidebarDemo />
37+
</ProtectedRoute>
38+
}
39+
>
2240
<Route index element={<Dashboard />} />
2341
<Route path="add-user" element={<AddUser />} />
2442
<Route path="add-task" element={<AddTask />} />
@@ -28,6 +46,9 @@ export default function AppRoutes() {
2846
<Route path="profile" element={<AdminProfile />} />
2947
<Route path="users/sheets/:userId" element={<AdminSheets />} />
3048
</Route>
49+
50+
{/* Catch-all fallback */}
51+
<Route path="*" element={<Login />} />
3152
</Routes>
3253
</ApiProvider>
3354
</AuthProvider>

0 commit comments

Comments
 (0)