forked from deriv-com/deriv-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthProvider.tsx
311 lines (267 loc) · 10.9 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { getAccountsFromLocalStorage, getActiveLoginIDFromLocalStorage, getToken } from '@deriv/utils';
import { AppIDConstants } from '@deriv-com/utils';
import { TSocketRequestPayload, TSocketResponseData, TSocketSubscribableEndpointNames } from '../types';
import { useAPIContext } from './APIProvider';
import { API_ERROR_CODES } from './constants';
import useAPI from './useAPI';
import useMutation from './useMutation';
// Define the type for the context state
type AuthContextType = {
loginIDKey?: string;
data: TSocketResponseData<'authorize'> | null | undefined;
loginid: string | null;
switchAccount: (loginid: string, forceRefresh?: boolean) => Promise<void>;
isLoading: boolean;
isSuccess: boolean;
isError: boolean;
refetch: () => void;
isFetching: boolean;
error: unknown;
isSwitching: boolean;
isInitializing: boolean;
subscribe: <T extends TSocketSubscribableEndpointNames>(
name: T,
payload?: TSocketRequestPayload<T>
) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe: (onData: (response: any) => void) => Promise<{ unsubscribe: () => Promise<void> }>;
};
};
type LoginToken = {
loginId: string;
token: string;
};
type AuthProviderProps = {
children: React.ReactNode;
cookieTimeout?: number;
loginIDKey?: string;
selectDefaultAccount?: (loginids: NonNullable<ReturnType<typeof getAccountsFromLocalStorage>>) => string;
logout?: () => Promise<void>;
};
type TAuthorizeError = ReturnType<typeof useMutation<'authorize'>>['error'];
// Create the context
const AuthContext = createContext<AuthContextType | undefined>(undefined);
function waitForLoginAndTokenWithTimeout(
cookieTimeout = 10000,
loginIDKey?: string,
selectDefaultAccount?: (loginids: NonNullable<ReturnType<typeof getAccountsFromLocalStorage>>) => string
) {
// Default timeout of 10 seconds
let timeoutHandle: NodeJS.Timeout | undefined,
cookieTimeoutHandle: NodeJS.Timeout | undefined, // Handle for the cookieTimeout
rejectFunction: (reason?: string) => void; // To be used for rejecting the promise in case of a timeout or cookieTimeout expiry
const checkLogin = (
resolve: (value: { loginId: string; token: string }) => void,
reject: (reason?: string) => void
) => {
const loginId = getActiveLoginIDFromLocalStorage(loginIDKey);
const token = getToken(loginId as string);
const storedAccounts = getAccountsFromLocalStorage();
if (loginId && token) {
clearTimeout(timeoutHandle); // Clear the checkLogin timeout as we've succeeded
clearTimeout(cookieTimeoutHandle); // Clear the cookieTimeout as well
resolve({ loginId, token });
} else if (selectDefaultAccount && storedAccounts && Object.keys(storedAccounts).length > 0) {
const selectedLoginId = selectDefaultAccount(storedAccounts);
clearTimeout(timeoutHandle); // Clear the checkLogin timeout as we've succeeded
clearTimeout(cookieTimeoutHandle); // Clear the cookieTimeout as well
resolve({ loginId: selectedLoginId, token: getToken(selectedLoginId) || '' });
} else {
timeoutHandle = setTimeout(checkLogin, 100, resolve, reject);
}
};
// Function to clear the timeouts and reject the promise if called
const cleanup = () => {
clearTimeout(timeoutHandle);
clearTimeout(cookieTimeoutHandle);
rejectFunction('Operation cancelled');
};
const promise = new Promise<LoginToken>((resolve, reject) => {
rejectFunction = reject; // Assign reject function to be accessible outside promise scope for cleanup
// Set up the cookieTimeout to reject the promise if not resolved in time
cookieTimeoutHandle = setTimeout(() => {
cleanup(); // Cleanup and reject the promise
reject(new Error('Waiting for login or token timed out'));
}, cookieTimeout);
checkLogin(resolve, reject);
});
return {
promise,
cleanup,
};
}
const AuthProvider = ({ loginIDKey, children, cookieTimeout, selectDefaultAccount, logout }: AuthProviderProps) => {
const [loginid, setLoginid] = useState<string | null>(null);
const { mutateAsync } = useMutation('authorize');
const { queryClient, setOnReconnected, setOnConnected, wsClient, createNewWSConnection } = useAPIContext();
const [isLoading, setIsLoading] = useState(true);
const [isSwitching, setIsSwitching] = useState(false);
const [isInitializing, setIsInitializing] = useState(true);
const [isSuccess, setIsSuccess] = useState(false);
const [isError, setIsError] = useState(false);
const [isFetching, setIsFetching] = useState(false);
const [isAuthorized, setIsAuthorized] = useState(false);
const [data, setData] = useState<TSocketResponseData<'authorize'> | null>();
const { subscribe: _subscribe } = useAPI();
const subscribe = useCallback(
<T extends TSocketSubscribableEndpointNames>(name: T, payload?: TSocketRequestPayload<T>) => {
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe: (onData: (response: any) => void) => {
return wsClient?.subscribe(name, payload, onData);
},
};
},
[wsClient, isAuthorized]
);
const processAuthorizeResponse = useCallback(
(authorizeResponse: TSocketResponseData<'authorize'>) => {
setData(authorizeResponse);
const activeLoginID = authorizeResponse.authorize?.loginid;
if (!activeLoginID) return;
setLoginid(activeLoginID);
const accountList = authorizeResponse.authorize?.account_list;
if (!accountList) return;
const activeAccount = accountList.find(acc => acc.loginid === activeLoginID);
if (!activeAccount) return;
localStorage.setItem(loginIDKey ?? 'active_loginid', activeLoginID);
sessionStorage.setItem(loginIDKey ?? 'active_loginid', activeLoginID);
const isDemo = activeAccount.is_virtual;
const shouldCreateNewWSConnection =
(isDemo && wsClient?.endpoint === AppIDConstants.environments.real) ||
(!isDemo && wsClient?.endpoint === AppIDConstants.environments.demo);
if (shouldCreateNewWSConnection) {
createNewWSConnection();
}
},
[loginIDKey, wsClient?.endpoint, createNewWSConnection]
);
useEffect(() => {
setOnConnected(() => {
initialize();
});
}, []);
useEffect(() => {
setOnReconnected(async () => {
setIsAuthorized(false);
await mutateAsync({ payload: { authorize: getToken(loginid || '') ?? '' } });
setIsAuthorized(true);
});
}, [loginid]);
function initialize() {
setIsLoading(true);
setIsInitializing(true);
setIsSuccess(false);
const { promise, cleanup } = waitForLoginAndTokenWithTimeout(cookieTimeout, loginIDKey, selectDefaultAccount);
let isMounted = true;
promise
.then(async ({ token }) => {
setIsLoading(true);
setIsInitializing(true);
setIsFetching(true);
setIsAuthorized(false);
await mutateAsync({ payload: { authorize: token || '' } })
.then(res => {
setIsAuthorized(true);
processAuthorizeResponse(res);
setIsLoading(false);
setIsInitializing(false);
setIsSuccess(true);
setLoginid(res?.authorize?.loginid ?? '');
})
.catch(async (e: TAuthorizeError) => {
if (e?.error.code === API_ERROR_CODES.DISABLED_ACCOUNT) {
await logout?.();
}
setIsLoading(false);
setIsInitializing(false);
setIsError(true);
})
.finally(() => {
setIsLoading(false);
setIsInitializing(false);
setIsFetching(false);
});
})
.catch(() => {
if (isMounted) {
setIsAuthorized(false);
setIsLoading(false);
setIsInitializing(false);
setIsError(true);
}
});
return () => {
isMounted = false;
cleanup();
};
}
const switchAccount = useCallback(
async (newLoginId: string, forceRefresh?: boolean) => {
if (newLoginId === loginid && !forceRefresh) {
return;
}
queryClient.cancelQueries();
setIsLoading(true);
setIsSwitching(true);
setIsAuthorized(false);
try {
const authorizeResponse = await mutateAsync({ payload: { authorize: getToken(newLoginId) ?? '' } });
setIsAuthorized(true);
setLoginid(newLoginId);
processAuthorizeResponse(authorizeResponse);
} catch (e: unknown) {
if (typeof e === 'object' && (e as TAuthorizeError)?.error.code === API_ERROR_CODES.DISABLED_ACCOUNT) {
await logout?.();
}
} finally {
setIsLoading(false);
setIsSwitching(false);
}
},
[loginid, logout, mutateAsync, processAuthorizeResponse, queryClient]
);
const refetch = useCallback(() => {
switchAccount(loginid as string);
}, [loginid, switchAccount]);
const value = useMemo(() => {
return {
data,
switchAccount,
refetch,
isLoading,
isError,
isFetching,
isSuccess: isSuccess && !isLoading,
error: isError,
loginid,
isSwitching,
isInitializing,
subscribe,
logout,
createNewWSConnection,
};
}, [
data,
switchAccount,
refetch,
isLoading,
isError,
isFetching,
isSuccess,
loginid,
logout,
createNewWSConnection,
subscribe,
]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export default AuthProvider;
export const useAuthContext = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuthContext must be used within APIProvider');
}
return context;
};