source: frontend/src/pages/ProtectedRoute.js@ 84249b1

Last change on this file since 84249b1 was 84249b1, checked in by MBK <marija.karapandzova@…>, 4 months ago

Add authentication and role-based route protection and add Dashboard page

  • Property mode set to 100644
File size: 652 bytes
Line 
1import React from 'react';
2import { Navigate } from 'react-router-dom';
3
4function ProtectedRoute({ children, requiredRoles = [] }) {
5 const token = localStorage.getItem('token');
6 const userStr = localStorage.getItem('user');
7
8 // If no token, redirect to login
9 if (!token) {
10 return <Navigate to="/login" replace />;
11 }
12
13 // If roles are specified and user's role is not in the list, redirect to dashboard
14 if (requiredRoles.length > 0 && userStr) {
15 const user = JSON.parse(userStr);
16 if (!requiredRoles.includes(user.role)) {
17 return <Navigate to="/" replace />;
18 }
19 }
20
21 return children;
22}
23
24export default ProtectedRoute;
Note: See TracBrowser for help on using the repository browser.