1 |
8c45ccb0
|
hrubyjar
|
import { useRouter } from 'next/router';
|
2 |
|
|
import { useEffect } from 'react';
|
3 |
|
|
import { getToken } from '../utils/login';
|
4 |
|
|
|
5 |
|
|
/**
|
6 |
|
|
* Performs redirect when user is unauthenticated.
|
7 |
|
|
* @param path path where to redirect
|
8 |
|
|
* @returns redirecting?
|
9 |
|
|
*/
|
10 |
|
|
const useUnauthRedirect = (path: string): boolean => {
|
11 |
|
|
const router = useRouter();
|
12 |
|
|
let tokenEmpty = false;
|
13 |
|
|
useEffect(() => {
|
14 |
|
|
async function checkToken() {
|
15 |
|
|
const empty = (await getToken()) === '';
|
16 |
|
|
if (tokenEmpty) {
|
17 |
|
|
router.push(path);
|
18 |
|
|
}
|
19 |
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
20 |
|
|
tokenEmpty = empty;
|
21 |
|
|
}
|
22 |
|
|
checkToken();
|
23 |
|
|
}, [path, router]);
|
24 |
|
|
|
25 |
|
|
return tokenEmpty;
|
26 |
|
|
};
|
27 |
|
|
|
28 |
|
|
export default useUnauthRedirect;
|