-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Session.js
385 lines (357 loc) · 12.9 KB
/
Session.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
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 API from '../API';
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 {translateLocal} from '../translate';
import * as Network from '../Network';
import UnreadIndicatorUpdater from '../UnreadIndicatorUpdater';
import Timers from '../Timers';
import * as Pusher from '../Pusher/pusher';
import NetworkConnection from '../NetworkConnection';
import {getUserDetails} from './User';
import {isNumericWithSpecialChars} from '../ValidationUtils';
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, {
shouldShowComposeInput: true,
..._.pick(data, 'authToken', 'accountID', 'email', 'encryptedAuthToken'),
});
}
/**
* Create an account for the user logging in.
* This will send them a notification with a link to click on to validate the account and set a password
*
* @param {String} login
*/
function createAccount(login) {
Onyx.merge(ONYXKEYS.SESSION, {error: ''});
API.User_SignUp({
email: login,
}).then((response) => {
if (response.jsonCode !== 200) {
let errorMessage = response.message || `Unknown API Error: ${response.jsonCode}`;
if (!response.message && response.jsonCode === 405) {
errorMessage = 'Cannot create an account that is under a controlled domain';
}
Onyx.merge(ONYXKEYS.SESSION, {error: errorMessage});
Onyx.merge(ONYXKEYS.CREDENTIALS, {login: null});
}
});
}
/**
* Clears the Onyx store and redirects user to the sign in page
*/
function signOut() {
Log.info('Flushing logs before signing out', true, {}, true);
if (credentials && credentials.autoGeneratedLogin) {
// Clean up the login that we created
API.DeleteLogin({
partnerUserID: credentials.autoGeneratedLogin,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
doNotRetry: true,
})
.catch(error => Onyx.merge(ONYXKEYS.SESSION, {error: error.message}));
}
Timing.clearData();
redirectToSignIn();
Log.info('Redirecting to Sign In because signOut() was called');
}
/**
* Reopen the account and send the user a link to set password
*
* @param {String} [login]
*/
function reopenAccount(login = credentials.login) {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: true});
API.User_ReopenAccount({email: login})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
}
/**
* Resend the validation link to the user that is validating their account
*
* @param {String} [login]
*/
function resendValidationLink(login = credentials.login) {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: true});
API.ResendValidateCode({email: login})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
}
/**
* Checks the API to see if an account exists for the given login
*
* @param {String} login
*/
function fetchAccountDetails(login) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, loading: true});
API.GetAccountStatus({email: login, forceNetworkRequest: true})
.then((response) => {
if (response.jsonCode === 200) {
Onyx.merge(ONYXKEYS.CREDENTIALS, {
login: response.normalizedLogin,
});
Onyx.merge(ONYXKEYS.ACCOUNT, {
accountExists: response.accountExists,
requiresTwoFactorAuth: response.requiresTwoFactorAuth,
validated: response.validated,
closed: response.isClosed,
forgotPassword: false,
});
if (!response.accountExists) {
createAccount(login);
} else if (response.isClosed) {
reopenAccount(login);
} else if (!response.validated) {
resendValidationLink(login);
}
} else if (response.jsonCode === 402) {
Onyx.merge(ONYXKEYS.ACCOUNT, {
error: isNumericWithSpecialChars(login)
? translateLocal('messages.errorMessageInvalidPhone')
: translateLocal('loginForm.error.invalidFormatEmailLogin'),
});
} else {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: response.message});
}
})
.catch(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: translateLocal('session.offlineMessageRetry')});
})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
}
/**
*
* 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} encryptedAuthToken – Not required for the CreateLogin API call, but passed to setSuccessfulSignInData
* @param {String} email
* @return {Promise}
*/
function createTemporaryLogin(authToken, encryptedAuthToken, email) {
const autoGeneratedLogin = Str.guid('expensify.cash-');
const autoGeneratedPassword = Str.guid();
return API.CreateLogin({
authToken,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
partnerUserID: autoGeneratedLogin,
partnerUserSecret: autoGeneratedPassword,
doNotRetry: true,
forceNetworkRequest: true,
email,
})
.then((createLoginResponse) => {
if (createLoginResponse.jsonCode !== 200) {
throw new Error(createLoginResponse.message);
}
setSuccessfulSignInData({...createLoginResponse, encryptedAuthToken});
// If we have an old generated login for some reason
// we should delete it before storing the new details
if (credentials && credentials.autoGeneratedLogin) {
API.DeleteLogin({
partnerUserID: credentials.autoGeneratedLogin,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
doNotRetry: true,
})
.catch(Log.info);
}
Onyx.merge(ONYXKEYS.CREDENTIALS, {
autoGeneratedLogin,
autoGeneratedPassword,
});
Network.unpauseRequestQueue();
return createLoginResponse;
})
.catch((error) => {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: error.message});
})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: 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) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, loading: true});
API.Authenticate({
useExpensifyLogin: true,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
partnerUserID: credentials.login,
partnerUserSecret: password,
twoFactorAuthCode,
email: credentials.login,
})
.then((authenticateResponse) => {
const {authToken, encryptedAuthToken, email} = authenticateResponse;
createTemporaryLogin(authToken, encryptedAuthToken, email);
})
.catch((error) => {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: translateLocal(error.message), loading: false});
});
}
/**
* Uses a short lived authToken to continue a user's session from OldDot
*
* @param {String} accountID
* @param {String} email
* @param {String} shortLivedToken
* @param {string} encryptedAuthToken
*/
function signInWithShortLivedToken(accountID, email, shortLivedToken, encryptedAuthToken) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, loading: true});
createTemporaryLogin(shortLivedToken, encryptedAuthToken, email).then((response) => {
Onyx.merge(ONYXKEYS.SESSION, {
authToken: shortLivedToken,
accountID,
email,
});
if (response.jsonCode === 200) {
getUserDetails();
Onyx.merge(ONYXKEYS.ACCOUNT, {success: true});
} else {
const error = lodashGet(response, 'message', 'Unable to login.');
Onyx.merge(ONYXKEYS.ACCOUNT, {error});
}
}).finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
}
/**
* User forgot the password so let's send them the link to reset their password
*/
function resetPassword() {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: true, forgotPassword: true});
API.ResetPassword({email: credentials.login})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
}
/**
* Set the password for the current 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} validateCode
* @param {String} accountID
*/
function setPassword(password, validateCode, accountID) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, loading: true});
API.SetPassword({
password,
validateCode,
accountID,
})
.then((response) => {
if (response.jsonCode === 200) {
createTemporaryLogin(response.authToken, response.encryptedAuthToken, response.email);
return;
}
// This request can fail if the password is not complex enough
Onyx.merge(ONYXKEYS.ACCOUNT, {error: response.message});
})
.catch((response) => {
if (response.title === CONST.PASSWORD_PAGE.ERROR.VALIDATE_CODE_FAILED) {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: translateLocal('setPasswordPage.accountNotValidated')});
}
})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
}
/**
* This is used when a user clicks on a link from e.com that goes to this application. We want the user to be able to
* be automatically logged into this app. If the user is not already logged into this app, then this method is called
* in order to retrieve an authToken from e.com and be signed in.
*
* @param {String} accountID
* @param {String} validateCode
* @param {String} [twoFactorAuthCode]
*/
function continueSessionFromECom(accountID, validateCode, twoFactorAuthCode) {
API.AuthenticateWithAccountID({
accountID,
validateCode,
twoFactorAuthCode,
}).then((data) => {
// If something failed, it doesn't really matter what, send the user to the sign in form to log in normally
if (data.jsonCode !== 200) {
Navigation.navigate(ROUTES.HOME);
return;
}
setSuccessfulSignInData(data);
});
}
/**
* 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();
}
export {
continueSessionFromECom,
fetchAccountDetails,
setPassword,
signIn,
signInWithShortLivedToken,
signOut,
reopenAccount,
resendValidationLink,
resetPassword,
clearSignInData,
cleanupSession,
};