-
Notifications
You must be signed in to change notification settings - Fork 3
/
AuthProvider.tsx
94 lines (81 loc) · 2.4 KB
/
AuthProvider.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
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { Context } from '../context/store';
import { Route, Routes } from 'react-router-dom';
import { parseCssDark } from '../utils/common';
import { setUser } from '../redux/actions';
import { useDispatch } from 'react-redux';
import GeneralApi from '../api/GeneralApi';
import Login from 'pages/login/Login';
import React, { useContext, useEffect } from 'react';
import UserApi from '../api/UserApi';
const AuthProvider = (props: any) => {
const reduxDispatch = useDispatch();
const [store, dispatch] = useContext(Context);
const { isLogged } = store;
const setContext = (type: string, payload: any) => {
dispatch({ type, payload });
};
const handleDemoRedirect = () => {
const query = new URLSearchParams(window.location.search);
const param = query.get('demo');
if (param) {
window.localStorage.setItem('apiUrl', 'https://demo.bloben.com/api');
window.env.apiUrl = 'https://demo.bloben.com/api';
window.location.replace('/calendar');
}
};
const checkLogin = async (): Promise<void> => {
if (!window.env?.apiUrl) {
setContext('isLogged', false);
setContext('isAppStarting', false);
handleDemoRedirect();
return;
}
try {
const response = await UserApi.getAccount();
if (response.data.userID) {
setContext('isLogged', true);
setContext('isAppStarting', false);
reduxDispatch(
setUser({
id: response.data.userID,
username: response.data.username,
})
);
} else {
setContext('isAppStarting', false);
}
} catch (e: any) {
if (e?.response.status === 401) {
setContext('isLogged', false);
setContext('isAppStarting', false);
return;
}
setContext('isLogged', true);
setContext('isAppStarting', false);
}
};
const getApiVersion = async () => {
if (!window.env?.apiUrl) {
setContext('isLogged', false);
return;
}
const response = await GeneralApi.getApiVersion();
setContext('version', response?.data);
};
// check login on load
useEffect(() => {
checkLogin();
getApiVersion();
}, []);
return (
<div className={parseCssDark('Surface', store.isDark)}>
<Routes>
<Route
path={'/calendar'}
element={!isLogged ? <Login /> : props.children}
/>
</Routes>
</div>
);
};
export default AuthProvider;