-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathAdminRoute.tsx
More file actions
38 lines (30 loc) · 1.03 KB
/
AdminRoute.tsx
File metadata and controls
38 lines (30 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { ReactNode, useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '../../services/actions/types';
import { AppDispatch, checkAuthenticated } from '../../services/actions/auth';
import Spinner from '../LoadingSpinner/LoadingSpinner';
interface AdminRouteProps {
children: ReactNode;
}
const AdminRoute = ({ children }: AdminRouteProps) => {
const location = useLocation();
const dispatch = useDispatch<AppDispatch>();
const { isAuthenticated, isSuperuser } = useSelector((state: RootState) => state.auth);
useEffect(() => {
if (isAuthenticated === null) {
dispatch(checkAuthenticated());
}
}, [dispatch, isAuthenticated]);
if (isAuthenticated === null) {
return <Spinner />;
}
if (!isAuthenticated) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
if (!isSuperuser) {
return <Navigate to="/" replace />;
}
return children;
};
export default AdminRoute;