-
Notifications
You must be signed in to change notification settings - Fork 3k
/
index.js
589 lines (544 loc) · 18.1 KB
/
index.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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import Onyx from 'react-native-onyx';
import Str from 'expensify-common/lib/str';
import _ from 'underscore';
import lodashGet from 'lodash/get';
import ONYXKEYS from '../../../ONYXKEYS';
import redirectToSignIn from '../SignInRedirect';
import * as DeprecatedAPI from '../../deprecatedAPI';
import CONFIG from '../../../CONFIG';
import Log from '../../Log';
import PushNotification from '../../Notification/PushNotification';
import Timing from '../Timing';
import CONST from '../../../CONST';
import Navigation from '../../Navigation/Navigation';
import ROUTES from '../../../ROUTES';
import * as Localize from '../../Localize';
import UnreadIndicatorUpdater from '../../UnreadIndicatorUpdater';
import Timers from '../../Timers';
import * as Pusher from '../../Pusher/pusher';
import NetworkConnection from '../../NetworkConnection';
import * as User from '../User';
import * as Authentication from '../../Authentication';
import * as Welcome from '../Welcome';
import * as API from '../../API';
import * as NetworkStore from '../../Network/NetworkStore';
import DateUtils from '../../DateUtils';
let credentials = {};
Onyx.connect({
key: ONYXKEYS.CREDENTIALS,
callback: val => credentials = val,
});
/**
* Sets API data in the store when we make a successful "Authenticate"/"CreateLogin" request
*
* @param {Object} data
* @param {String} data.accountID
* @param {String} data.authToken
* @param {String} data.email
*/
function setSuccessfulSignInData(data) {
PushNotification.register(data.accountID);
Onyx.merge(ONYXKEYS.SESSION, {
errors: null,
..._.pick(data, 'authToken', 'accountID', 'email', 'encryptedAuthToken'),
});
Onyx.set(ONYXKEYS.SHOULD_SHOW_COMPOSE_INPUT, true);
}
/**
* Clears the Onyx store and redirects user to the sign in page
*/
function signOut() {
Log.info('Flushing logs before signing out', true, {}, true);
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: ONYXKEYS.SESSION,
value: null,
},
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: ONYXKEYS.CREDENTIALS,
value: null,
},
];
API.write('LogOut', {
// Send current authToken because we will immediately clear it once triggering this command
authToken: NetworkStore.getAuthToken(),
partnerUserID: lodashGet(credentials, 'autoGeneratedLogin', ''),
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
shouldRetry: false,
}, {optimisticData});
Timing.clearData();
}
function signOutAndRedirectToSignIn() {
signOut();
redirectToSignIn();
Log.info('Redirecting to Sign In because signOut() was called');
}
/**
* Resend the validation link to the user that is validating their account
*
* @param {String} [login]
*/
function resendValidationLink(login = credentials.login) {
const optimisticData = [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: true,
errors: null,
message: null,
},
}];
const successData = [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
message: Localize.translateLocal('resendValidationForm.linkHasBeenResent'),
},
}];
const failureData = [{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
message: null,
},
}];
API.write('RequestAccountValidationLink', {email: login}, {optimisticData, successData, failureData});
}
/**
* Checks the API to see if an account exists for the given login
*
* @param {String} login
*/
function beginSignIn(login) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
...CONST.DEFAULT_ACCOUNT_DATA,
isLoading: true,
},
},
];
const successData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
];
const failureData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
errors: {
[DateUtils.getMicroseconds()]: Localize.translateLocal('loginForm.cannotGetAccountDetails'),
},
},
},
];
API.read('BeginSignIn', {email: login}, {optimisticData, successData, failureData});
}
/**
*
* Will create a temporary login for the user in the passed authenticate response which is used when
* re-authenticating after an authToken expires.
*
* @param {String} authToken
* @param {String} email
* @return {Promise}
*/
function createTemporaryLogin(authToken, email) {
const autoGeneratedLogin = Str.guid('expensify.cash-');
const autoGeneratedPassword = Str.guid();
return DeprecatedAPI.CreateLogin({
authToken,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
partnerUserID: autoGeneratedLogin,
partnerUserSecret: autoGeneratedPassword,
shouldRetry: false,
forceNetworkRequest: true,
email,
includeEncryptedAuthToken: true,
})
.then((createLoginResponse) => {
if (createLoginResponse.jsonCode !== 200) {
Onyx.merge(ONYXKEYS.ACCOUNT, {errors: {[DateUtils.getMicroseconds()]: Localize.translate('createLoginResponse.message')}});
return createLoginResponse;
}
setSuccessfulSignInData(createLoginResponse);
// If we have an old generated login for some reason
// we should delete it before storing the new details
if (credentials && credentials.autoGeneratedLogin) {
DeprecatedAPI.DeleteLogin({
partnerUserID: credentials.autoGeneratedLogin,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
shouldRetry: false,
})
.then((response) => {
if (response.jsonCode === CONST.JSON_CODE.SUCCESS) {
return;
}
Log.hmmm('[Session] Unable to delete login', false, {message: response.message, jsonCode: response.jsonCode});
});
}
Onyx.merge(ONYXKEYS.CREDENTIALS, {
autoGeneratedLogin,
autoGeneratedPassword,
});
return createLoginResponse;
})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {isLoading: false});
});
}
/**
* Sign the user into the application. This will first authenticate their account
* then it will create a temporary login for them which is used when re-authenticating
* after an authToken expires.
*
* @param {String} password
* @param {String} [twoFactorAuthCode]
*/
function signIn(password, twoFactorAuthCode) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
...CONST.DEFAULT_ACCOUNT_DATA,
isLoading: true,
},
},
];
const successData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
];
const failureData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
];
API.write('SigninUser', {email: credentials.login, password, twoFactorAuthCode}, {optimisticData, successData, failureData});
}
/**
* Uses a short lived authToken to continue a user's session from OldDot
*
* @param {String} email
* @param {String} shortLivedToken
* @param {String} exitTo
*/
function signInWithShortLivedToken(email, shortLivedToken) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, isLoading: true});
createTemporaryLogin(shortLivedToken, email)
.then((response) => {
if (response.jsonCode !== CONST.JSON_CODE.SUCCESS) {
return;
}
User.getUserDetails();
Onyx.merge(ONYXKEYS.ACCOUNT, {success: true});
}).finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {isLoading: false});
});
}
/**
* User forgot the password so let's send them the link to reset their password
*/
function resetPassword() {
API.write('RequestPasswordReset', {
email: credentials.login,
},
{
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
errors: null,
forgotPassword: true,
message: null,
},
},
],
});
}
function resendResetPassword() {
API.write('ResendRequestPasswordReset', {
email: credentials.login,
},
{
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: true,
forgotPassword: true,
message: null,
errors: null,
},
},
],
successData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
message: Localize.translateLocal('resendValidationForm.linkHasBeenResent'),
},
},
],
failureData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
],
});
}
function invalidateCredentials() {
Onyx.merge(ONYXKEYS.CREDENTIALS, {autoGeneratedLogin: '', autoGeneratedPassword: ''});
}
function invalidateAuthToken() {
NetworkStore.setAuthToken('pizza');
Onyx.merge(ONYXKEYS.SESSION, {authToken: 'pizza'});
}
/**
* Clear the credentials and partial sign in session so the user can taken back to first Login step
*/
function clearSignInData() {
Onyx.multiSet({
[ONYXKEYS.ACCOUNT]: null,
[ONYXKEYS.CREDENTIALS]: null,
});
}
/**
* Put any logic that needs to run when we are signed out here. This can be triggered when the current tab or another tab signs out.
*/
function cleanupSession() {
// We got signed out in this tab or another so clean up any subscriptions and timers
NetworkConnection.stopListeningForReconnect();
UnreadIndicatorUpdater.stopListeningForReportChanges();
PushNotification.deregister();
PushNotification.clearNotifications();
Pusher.disconnect();
Timers.clearAll();
Welcome.resetReadyCheck();
}
function clearAccountMessages() {
Onyx.merge(ONYXKEYS.ACCOUNT, {
success: '',
errors: null,
message: null,
isLoading: false,
});
}
/**
* Calls change password and signs if successful. Otherwise, we request a new magic link
* if we know the account email. Otherwise or finally we redirect to the root of the nav.
* @param {String} authToken
* @param {String} password
*/
function changePasswordAndSignIn(authToken, password) {
Onyx.merge(ONYXKEYS.ACCOUNT, {validateSessionExpired: false});
DeprecatedAPI.ChangePassword({
authToken,
password,
})
.then((responsePassword) => {
if (responsePassword.jsonCode === 200) {
signIn(password);
return;
}
if (responsePassword.jsonCode === CONST.JSON_CODE.NOT_AUTHENTICATED && !credentials.login) {
// authToken has expired, and we don't have the email set to request a new magic link.
// send user to login page to enter email.
Navigation.navigate(ROUTES.HOME);
return;
}
if (responsePassword.jsonCode === CONST.JSON_CODE.NOT_AUTHENTICATED) {
// authToken has expired, and we have the account email, so we request a new magic link.
Onyx.merge(ONYXKEYS.ACCOUNT, {errors: null});
resetPassword();
Navigation.navigate(ROUTES.HOME);
return;
}
Onyx.merge(ONYXKEYS.SESSION, {errors: {[DateUtils.getMicroseconds()]: Localize.translateLocal('setPasswordPage.passwordNotSet')}});
});
}
/**
* Updates a password and authenticates them
* @param {Number} accountID
* @param {String} validateCode
* @param {String} password
*/
function updatePasswordAndSignin(accountID, validateCode, password) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: true,
errors: null,
},
},
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.SESSION,
value: {
errors: null,
},
},
];
const successData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
errors: null,
},
},
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.SESSION,
value: {
errors: null,
},
},
];
const failureData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
];
API.write('UpdatePasswordAndSignin', {
accountID, validateCode, password,
}, {optimisticData, successData, failureData});
}
/**
* @param {Number} accountID
* @param {String} validateCode
* @param {String} login
* @param {String} authToken
*/
function validateEmail(accountID, validateCode) {
Onyx.merge(ONYXKEYS.SESSION, {errors: null});
DeprecatedAPI.ValidateEmail({
accountID,
validateCode,
})
.then((responseValidate) => {
if (responseValidate.jsonCode === 200) {
Onyx.merge(ONYXKEYS.CREDENTIALS, {login: responseValidate.email, authToken: responseValidate.authToken});
return;
}
if (responseValidate.jsonCode === 666) {
Onyx.merge(ONYXKEYS.ACCOUNT, {validated: true});
}
if (responseValidate.jsonCode === 401) {
Onyx.merge(ONYXKEYS.SESSION, {errors: {[DateUtils.getMicroseconds()]: Localize.translate('setPasswordPage.setPasswordLinkInvalid')}});
}
});
}
// It's necessary to throttle requests to reauthenticate since calling this multiple times will cause Pusher to
// reconnect each time when we only need to reconnect once. This way, if an authToken is expired and we try to
// subscribe to a bunch of channels at once we will only reauthenticate and force reconnect Pusher once.
const reauthenticatePusher = _.throttle(() => {
Log.info('[Pusher] Re-authenticating and then reconnecting');
Authentication.reauthenticate('AuthenticatePusher')
.then(Pusher.reconnect)
.catch(() => {
console.debug(
'[PusherConnectionManager]',
'Unable to re-authenticate Pusher because we are offline.',
);
});
}, 5000, {trailing: false});
/**
* @param {String} socketID
* @param {String} channelName
* @param {Function} callback
*/
function authenticatePusher(socketID, channelName, callback) {
Log.info('[PusherAuthorizer] Attempting to authorize Pusher', false, {channelName});
// We use makeRequestWithSideEffects here because we need to authorize to Pusher (an external service) each time a user connects to any channel.
// eslint-disable-next-line rulesdir/no-api-side-effects-method
API.makeRequestWithSideEffects('AuthenticatePusher', {
socket_id: socketID,
channel_name: channelName,
shouldRetry: false,
forceNetworkRequest: true,
}).then((response) => {
if (response.jsonCode === CONST.JSON_CODE.NOT_AUTHENTICATED) {
Log.hmmm('[PusherAuthorizer] Unable to authenticate Pusher because authToken is expired');
callback(new Error('Pusher failed to authenticate because authToken is expired'), {auth: ''});
// Attempt to refresh the authToken then reconnect to Pusher
reauthenticatePusher();
return;
}
if (response.jsonCode !== CONST.JSON_CODE.SUCCESS) {
Log.hmmm('[PusherAuthorizer] Unable to authenticate Pusher for reason other than expired session');
callback(new Error(`Pusher failed to authenticate because code: ${response.jsonCode} message: ${response.message}`), {auth: ''});
return;
}
Log.info(
'[PusherAuthorizer] Pusher authenticated successfully',
false,
{channelName},
);
callback(null, response);
}).catch((error) => {
Log.hmmm('[PusherAuthorizer] Unhandled error: ', {channelName, error});
callback(new Error('AuthenticatePusher request failed'), {auth: ''});
});
}
export {
beginSignIn,
updatePasswordAndSignin,
signIn,
signInWithShortLivedToken,
signOut,
signOutAndRedirectToSignIn,
resendValidationLink,
resetPassword,
resendResetPassword,
clearSignInData,
cleanupSession,
clearAccountMessages,
validateEmail,
authenticatePusher,
reauthenticatePusher,
changePasswordAndSignIn,
invalidateCredentials,
invalidateAuthToken,
};