-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthContext.js
62 lines (55 loc) · 1.48 KB
/
AuthContext.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import React, { useState, createContext } from 'react';
import { useHistory } from 'react-router-dom';
const AuthContext = createContext();
AuthContext.displayName = 'AuthContext';
const { Provider } = AuthContext;
const AuthProvider = ({ children }) => {
const history = useHistory();
const userInfo = localStorage.getItem('userInfo');
const expiresAt = localStorage.getItem('expiresAt');
const [authState, setAuthState] = useState({
token: null,
userInfo: userInfo ? JSON.parse(userInfo) : {},
expiresAt
})
const setAuthInfo = ({ token, userInfo, expiresAt }) => {
localStorage.setItem('userInfo', JSON.stringify(userInfo));
localStorage.setItem('expiresAt', expiresAt);
setAuthState({
token,
userInfo,
expiresAt
})
}
const logout = () => {
localStorage.removeItem('userInfo');
localStorage.removeItem('expiresAt');
setAuthState({
token: null,
userInfo: {},
expiresAt: null
})
history.push('/login');
}
const isAuthenticated = () => {
if(!authState.token || !authState.expiresAt) {
return false;
}
return new Date().getTime() / 1000 < authState.expiresAt;
}
const isAdmin = () => authState.userInfo.role === 'admin';
return (
<Provider
value={{
authState,
setAuthState: authInfo => setAuthInfo(authInfo),
isAuthenticated,
logout,
isAdmin
}}
>
{children}
</Provider>
);
};
export { AuthContext, AuthProvider };