-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthRoute.tsx
More file actions
34 lines (27 loc) · 960 Bytes
/
AuthRoute.tsx
File metadata and controls
34 lines (27 loc) · 960 Bytes
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
import { FC } from 'react';
import { Navigate, Outlet, RouteProps, useLocation } from 'react-router';
import { useAuth } from './AuthContext';
const paths = ['', '/', '/login', '/logout'];
export const PREV_ROUTE = 'PREV_ROUTE';
export const AuthRoute: FC<RouteProps> = () => {
const { isAuthenticated, logout, isLoading, user } = useAuth();
const location = useLocation();
const prevRoute = window.localStorage.getItem(PREV_ROUTE);
const pathname = location.pathname;
if (!isAuthenticated && !isLoading) {
if (!prevRoute && pathname && !paths.includes(pathname)) {
window.localStorage.setItem(PREV_ROUTE, pathname);
}
logout();
return <Navigate to="/login" replace />;
}
if (user) {
if (prevRoute && pathname !== prevRoute) {
window.localStorage.removeItem(PREV_ROUTE);
return <Navigate to={prevRoute} />;
}
} else if (isLoading) {
return <div>Loading...</div>;
}
return <Outlet />;
};