-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProtectedRoute.tsx
27 lines (21 loc) · 1.03 KB
/
ProtectedRoute.tsx
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
import { Navigate, useLocation, useSearchParams } from 'react-router-dom'
import { useContext } from 'react';
import { UserContext } from './App.tsx';
import { ReactNode } from 'react';
import { signOut } from 'firebase/auth';
import { auth } from '../../server/firebase.ts';
export default function ProtectedRoute({ children, ifLoggedIn = true, redirectTo = '/login', includeRedirect = false }: { children?: ReactNode, ifLoggedIn?: boolean, redirectTo?: string, includeRedirect?: boolean }) {
const { user } = useContext(UserContext)
const [searchParams] = useSearchParams();
const from = searchParams.get('from')
// If signed in and redirect is to 'logout', then log out and redirect to 'login'
if (user && redirectTo == '/logout') {
redirectTo = '/login'
signOut(auth)
}
// Get the current path
const location = useLocation();
if (includeRedirect) redirectTo = `${redirectTo}?from=${location.pathname}`
else if (from) redirectTo = from
return ifLoggedIn == !user ? <Navigate to={redirectTo} /> : <>{children}</>
}