1
|
import React, { ReactNode, useContext, useEffect, useState } from 'react';
|
2
|
import { useRouter } from 'next/router';
|
3
|
import { LoggedUserContext } from '../../contexts/LoggedUserContext';
|
4
|
import { ERole } from '../../api';
|
5
|
|
6
|
export default function Auth({
|
7
|
minRole,
|
8
|
children,
|
9
|
}: {
|
10
|
minRole?: ERole | null;
|
11
|
children: ReactNode;
|
12
|
}) {
|
13
|
const { role, tokenExpiration, logout } = useContext(LoggedUserContext);
|
14
|
const [clientRender, setClientRender] = useState(false);
|
15
|
const router = useRouter();
|
16
|
|
17
|
function checkRole(): boolean {
|
18
|
if (!minRole) {
|
19
|
// no role required
|
20
|
return true;
|
21
|
}
|
22
|
|
23
|
return role === minRole ?? false;
|
24
|
}
|
25
|
|
26
|
useEffect(() => {
|
27
|
setClientRender(true);
|
28
|
}, []);
|
29
|
|
30
|
if (tokenExpiration?.isBefore(new Date())) {
|
31
|
// token has expired
|
32
|
|
33
|
(async () => {
|
34
|
await logout();
|
35
|
await router.push('/');
|
36
|
})();
|
37
|
}
|
38
|
|
39
|
if (clientRender && checkRole()) {
|
40
|
return <>{children}</>;
|
41
|
}
|
42
|
|
43
|
return null;
|
44
|
}
|