1
|
import React, { createContext, useEffect, useState } from 'react';
|
2
|
import moment, { Moment } from 'moment';
|
3
|
import { getTokenData, loginUser, logoutUser } from '../utils/login';
|
4
|
import { useRouter } from 'next/router';
|
5
|
import { ERole } from '../api';
|
6
|
|
7
|
interface ILoggedUserProvider {
|
8
|
login: (email: string, password: string) => Promise<boolean>;
|
9
|
logout: () => Promise<boolean>;
|
10
|
|
11
|
tokenExpiration?: Moment | null;
|
12
|
setTokenExpiration?: (newTokenExpiration: Moment | null) => void;
|
13
|
|
14
|
role?: ERole | undefined;
|
15
|
setRole?: (newRoles: ERole | undefined) => void;
|
16
|
|
17
|
refreshData?: () => Promise<void>;
|
18
|
}
|
19
|
|
20
|
export const LoggedUserContext = createContext<ILoggedUserProvider>({
|
21
|
login: async (username: string, password: string): Promise<boolean> => {
|
22
|
return false;
|
23
|
},
|
24
|
logout: async (): Promise<boolean> => {
|
25
|
return false;
|
26
|
},
|
27
|
});
|
28
|
|
29
|
const LoggedUserProvider = (props: { children: any }) => {
|
30
|
const [role, setRole] = useState<ERole>();
|
31
|
const [tokenExpiration, setTokenExpiration] = useState<Moment | null>(null);
|
32
|
const router = useRouter();
|
33
|
|
34
|
useEffect(() => {
|
35
|
loadData();
|
36
|
}, []);
|
37
|
|
38
|
async function loadData() {
|
39
|
const tokenData = await getTokenData();
|
40
|
if (!tokenData) {
|
41
|
setRole(undefined);
|
42
|
setTokenExpiration(null);
|
43
|
} else {
|
44
|
setRole(tokenData.role);
|
45
|
setTokenExpiration(moment(tokenData.expiration));
|
46
|
}
|
47
|
}
|
48
|
|
49
|
async function login(username: string, password: string): Promise<boolean> {
|
50
|
const res = await loginUser(username, password);
|
51
|
if (!res) {
|
52
|
return false;
|
53
|
}
|
54
|
|
55
|
await loadData();
|
56
|
|
57
|
return true;
|
58
|
}
|
59
|
|
60
|
async function logout(): Promise<boolean> {
|
61
|
const res = await logoutUser();
|
62
|
|
63
|
if (res) {
|
64
|
setRole(undefined);
|
65
|
}
|
66
|
await router.push('/');
|
67
|
return res;
|
68
|
}
|
69
|
|
70
|
return (
|
71
|
<LoggedUserContext.Provider
|
72
|
value={{
|
73
|
tokenExpiration,
|
74
|
setTokenExpiration,
|
75
|
role,
|
76
|
setRole,
|
77
|
refreshData: loadData,
|
78
|
login,
|
79
|
logout,
|
80
|
}}
|
81
|
>
|
82
|
{props.children}
|
83
|
</LoggedUserContext.Provider>
|
84
|
);
|
85
|
};
|
86
|
|
87
|
export default LoggedUserProvider;
|