-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathBaseValidateCodeForm.js
executable file
·438 lines (395 loc) · 17.5 KB
/
BaseValidateCodeForm.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
import {useIsFocused} from '@react-navigation/native';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import Button from '@components/Button';
import FormHelpMessage from '@components/FormHelpMessage';
import MagicCodeInput from '@components/MagicCodeInput';
import networkPropTypes from '@components/networkPropTypes';
import {withNetwork} from '@components/OnyxProvider';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import Text from '@components/Text';
import TextInput from '@components/TextInput';
import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import withToggleVisibilityView from '@components/withToggleVisibilityView';
import usePrevious from '@hooks/usePrevious';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus';
import compose from '@libs/compose';
import * as ErrorUtils from '@libs/ErrorUtils';
import * as ValidationUtils from '@libs/ValidationUtils';
import ChangeExpensifyLoginLink from '@pages/signin/ChangeExpensifyLoginLink';
import Terms from '@pages/signin/Terms';
import * as Session from '@userActions/Session';
import * as User from '@userActions/User';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
const propTypes = {
/* Onyx Props */
/** The details about the account that the user is signing in with */
account: PropTypes.shape({
/** Whether or not two-factor authentication is required */
requiresTwoFactorAuth: PropTypes.bool,
/** Whether or not a sign on form is loading (being submitted) */
isLoading: PropTypes.bool,
/** Whether or not the user has SAML enabled on their account */
isSAMLEnabled: PropTypes.bool,
/** Whether or not SAML is required on the account */
isSAMLRequired: PropTypes.bool,
}),
/** The credentials of the person signing in */
credentials: PropTypes.shape({
/** The login of the person signing in */
login: PropTypes.string,
}),
/** Session of currently logged in user */
session: PropTypes.shape({
/** Currently logged in user authToken */
authToken: PropTypes.string,
}),
/** Information about the network */
network: networkPropTypes.isRequired,
/** Specifies autocomplete hints for the system, so it can provide autofill */
autoComplete: PropTypes.oneOf(['sms-otp', 'one-time-code']).isRequired,
/** Determines if user is switched to using recovery code instead of 2fa code */
isUsingRecoveryCode: PropTypes.bool.isRequired,
/** Function to change `isUsingRecoveryCode` state when user toggles between 2fa code and recovery code */
setIsUsingRecoveryCode: PropTypes.func.isRequired,
...withLocalizePropTypes,
};
const defaultProps = {
account: {},
credentials: {},
session: {
authToken: null,
},
};
function BaseValidateCodeForm(props) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const isFocused = useIsFocused();
const [formError, setFormError] = useState({});
const [validateCode, setValidateCode] = useState(props.credentials.validateCode || '');
const [twoFactorAuthCode, setTwoFactorAuthCode] = useState('');
const [timeRemaining, setTimeRemaining] = useState(30);
const [recoveryCode, setRecoveryCode] = useState('');
const [needToClearError, setNeedToClearError] = useState(props.account.errors);
const prevRequiresTwoFactorAuth = usePrevious(props.account.requiresTwoFactorAuth);
const prevValidateCode = usePrevious(props.credentials.validateCode);
const inputValidateCodeRef = useRef();
const input2FARef = useRef();
const timerRef = useRef();
const hasError = Boolean(props.account) && !_.isEmpty(props.account.errors) && !needToClearError;
const isLoadingResendValidationForm = props.account.loadingForm === CONST.FORMS.RESEND_VALIDATE_CODE_FORM;
const shouldDisableResendValidateCode = props.network.isOffline || props.account.isLoading;
const isValidateCodeFormSubmitting =
props.account.isLoading && props.account.loadingForm === (props.account.requiresTwoFactorAuth ? CONST.FORMS.VALIDATE_TFA_CODE_FORM : CONST.FORMS.VALIDATE_CODE_FORM);
useEffect(() => {
if (!(inputValidateCodeRef.current && hasError && (props.session.autoAuthState === CONST.AUTO_AUTH_STATE.FAILED || props.account.isLoading))) {
return;
}
inputValidateCodeRef.current.blur();
}, [props.account.isLoading, props.session.autoAuthState, hasError]);
useEffect(() => {
if (!inputValidateCodeRef.current || !canFocusInputOnScreenFocus() || !props.isVisible || !isFocused) {
return;
}
inputValidateCodeRef.current.focus();
}, [props.isVisible, isFocused]);
useEffect(() => {
if (prevValidateCode || !props.credentials.validateCode) {
return;
}
setValidateCode(props.credentials.validateCode);
}, [props.credentials.validateCode, prevValidateCode]);
useEffect(() => {
if (!input2FARef.current || prevRequiresTwoFactorAuth || !props.account.requiresTwoFactorAuth) {
return;
}
input2FARef.current.focus();
}, [props.account.requiresTwoFactorAuth, prevRequiresTwoFactorAuth]);
useEffect(() => {
if (!inputValidateCodeRef.current || validateCode.length > 0) {
return;
}
inputValidateCodeRef.current.clear();
}, [validateCode]);
useEffect(() => {
if (!input2FARef.current || twoFactorAuthCode.length > 0) {
return;
}
input2FARef.current.clear();
}, [twoFactorAuthCode]);
useEffect(() => {
if (timeRemaining > 0) {
timerRef.current = setTimeout(() => {
setTimeRemaining(timeRemaining - 1);
}, 1000);
}
return () => {
clearTimeout(timerRef.current);
};
}, [timeRemaining]);
/**
* Handle text input and clear formError upon text change
*
* @param {String} text
* @param {String} key
*/
const onTextInput = (text, key) => {
let setInput;
if (key === 'validateCode') {
setInput = setValidateCode;
}
if (key === 'twoFactorAuthCode') {
setInput = setTwoFactorAuthCode;
}
if (key === 'recoveryCode') {
setInput = setRecoveryCode;
}
setInput(text);
setFormError((prevError) => ({...prevError, [key]: ''}));
if (props.account.errors) {
Session.clearAccountMessages();
}
};
/**
* Trigger the reset validate code flow and ensure the 2FA input field is reset to avoid it being permanently hidden
*/
const resendValidateCode = () => {
User.resendValidateCode(props.credentials.login);
inputValidateCodeRef.current.clear();
// Give feedback to the user to let them know the email was sent so that they don't spam the button.
setTimeRemaining(30);
};
/**
* Clear local sign in states
*/
const clearLocalSignInData = () => {
setTwoFactorAuthCode('');
setFormError({});
setValidateCode('');
props.setIsUsingRecoveryCode(false);
setRecoveryCode('');
};
/**
* Clears local and Onyx sign in states
*/
const clearSignInData = () => {
clearLocalSignInData();
Session.clearSignInData();
};
useEffect(() => {
if (!needToClearError) {
return;
}
if (props.account.errors) {
Session.clearAccountMessages();
return;
}
setNeedToClearError(false);
}, [props.account.errors, needToClearError]);
/**
* Switches between 2fa and recovery code, clears inputs and errors
*/
const switchBetween2faAndRecoveryCode = () => {
props.setIsUsingRecoveryCode(!props.isUsingRecoveryCode);
setRecoveryCode('');
setTwoFactorAuthCode('');
setFormError((prevError) => ({...prevError, recoveryCode: '', twoFactorAuthCode: ''}));
if (props.account.errors) {
Session.clearAccountMessages();
}
};
useEffect(() => {
if (!isLoadingResendValidationForm) {
return;
}
clearLocalSignInData();
// `clearLocalSignInData` is not required as a dependency, and adding it
// overcomplicates things requiring clearLocalSignInData function to use useCallback
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoadingResendValidationForm]);
/**
* Check that all the form fields are valid, then trigger the submit callback
*/
const validateAndSubmitForm = useCallback(() => {
if (props.account.isLoading) {
return;
}
const requiresTwoFactorAuth = props.account.requiresTwoFactorAuth;
if (requiresTwoFactorAuth) {
if (input2FARef.current) {
input2FARef.current.blur();
}
/**
* User could be using either recovery code or 2fa code
*/
if (!props.isUsingRecoveryCode) {
if (!twoFactorAuthCode.trim()) {
setFormError({twoFactorAuthCode: 'validateCodeForm.error.pleaseFillTwoFactorAuth'});
return;
}
if (!ValidationUtils.isValidTwoFactorCode(twoFactorAuthCode)) {
setFormError({twoFactorAuthCode: 'passwordForm.error.incorrect2fa'});
return;
}
} else {
if (!recoveryCode.trim()) {
setFormError({recoveryCode: 'recoveryCodeForm.error.pleaseFillRecoveryCode'});
return;
}
if (!ValidationUtils.isValidRecoveryCode(recoveryCode)) {
setFormError({recoveryCode: 'recoveryCodeForm.error.incorrectRecoveryCode'});
return;
}
}
} else {
if (inputValidateCodeRef.current) {
inputValidateCodeRef.current.blur();
}
if (!validateCode.trim()) {
setFormError({validateCode: 'validateCodeForm.error.pleaseFillMagicCode'});
return;
}
if (!ValidationUtils.isValidValidateCode(validateCode)) {
setFormError({validateCode: 'validateCodeForm.error.incorrectMagicCode'});
return;
}
}
setFormError({});
const recoveryCodeOr2faCode = props.isUsingRecoveryCode ? recoveryCode : twoFactorAuthCode;
const accountID = lodashGet(props.credentials, 'accountID');
if (accountID) {
Session.signInWithValidateCode(accountID, validateCode, recoveryCodeOr2faCode);
} else {
Session.signIn(validateCode, recoveryCodeOr2faCode);
}
}, [props.account, props.credentials, twoFactorAuthCode, validateCode, props.isUsingRecoveryCode, recoveryCode]);
return (
<>
{/* At this point, if we know the account requires 2FA we already successfully authenticated */}
{props.account.requiresTwoFactorAuth ? (
<View style={[styles.mv3]}>
{props.isUsingRecoveryCode ? (
<TextInput
shouldDelayFocus
accessibilityLabel={props.translate('recoveryCodeForm.recoveryCode')}
value={recoveryCode}
onChangeText={(text) => onTextInput(text, 'recoveryCode')}
maxLength={CONST.RECOVERY_CODE_LENGTH}
label={props.translate('recoveryCodeForm.recoveryCode')}
errorText={formError.recoveryCode ? props.translate(formError.recoveryCode) : ''}
hasError={hasError}
onSubmitEditing={validateAndSubmitForm}
autoFocus
/>
) : (
<MagicCodeInput
shouldDelayFocus
autoComplete={props.autoComplete}
ref={input2FARef}
label={props.translate('common.twoFactorCode')}
name="twoFactorAuthCode"
value={twoFactorAuthCode}
onChangeText={(text) => onTextInput(text, 'twoFactorAuthCode')}
onFulfill={validateAndSubmitForm}
maxLength={CONST.TFA_CODE_LENGTH}
errorText={formError.twoFactorAuthCode ? props.translate(formError.twoFactorAuthCode) : ''}
hasError={hasError}
autoFocus
key="twoFactorAuthCode"
/>
)}
{hasError && <FormHelpMessage message={ErrorUtils.getLatestErrorMessage(props.account)} />}
<PressableWithFeedback
style={[styles.mt2]}
onPress={switchBetween2faAndRecoveryCode}
underlayColor={theme.componentBG}
hoverDimmingValue={1}
pressDimmingValue={0.2}
disabled={isValidateCodeFormSubmitting}
role={CONST.ROLE.BUTTON}
accessibilityLabel={props.isUsingRecoveryCode ? props.translate('recoveryCodeForm.use2fa') : props.translate('recoveryCodeForm.useRecoveryCode')}
>
<Text style={[styles.link]}>{props.isUsingRecoveryCode ? props.translate('recoveryCodeForm.use2fa') : props.translate('recoveryCodeForm.useRecoveryCode')}</Text>
</PressableWithFeedback>
</View>
) : (
<View style={[styles.mv3]}>
<MagicCodeInput
autoComplete={props.autoComplete}
ref={inputValidateCodeRef}
label={props.translate('common.magicCode')}
name="validateCode"
value={validateCode}
onChangeText={(text) => onTextInput(text, 'validateCode')}
onFulfill={validateAndSubmitForm}
errorText={formError.validateCode ? props.translate(formError.validateCode) : ''}
hasError={hasError}
autoFocus
key="validateCode"
testID="validateCode"
/>
{hasError && <FormHelpMessage message={ErrorUtils.getLatestErrorMessage(props.account)} />}
<View style={[styles.alignItemsStart]}>
{timeRemaining > 0 && !props.network.isOffline ? (
<Text style={[styles.mt2]}>
{props.translate('validateCodeForm.requestNewCode')}
<Text style={[styles.textBlue]}>00:{String(timeRemaining).padStart(2, '0')}</Text>
</Text>
) : (
<PressableWithFeedback
style={[styles.mt2]}
onPress={resendValidateCode}
underlayColor={theme.componentBG}
disabled={shouldDisableResendValidateCode}
hoverDimmingValue={1}
pressDimmingValue={0.2}
role={CONST.ROLE.BUTTON}
accessibilityLabel={props.translate('validateCodeForm.magicCodeNotReceived')}
>
<Text style={[StyleUtils.getDisabledLinkStyles(shouldDisableResendValidateCode)]}>
{hasError ? props.translate('validateCodeForm.requestNewCodeAfterErrorOccurred') : props.translate('validateCodeForm.magicCodeNotReceived')}
</Text>
</PressableWithFeedback>
)}
</View>
</View>
)}
<View>
<Button
isDisabled={props.network.isOffline}
success
style={[styles.mv3]}
text={props.translate('common.signIn')}
isLoading={isValidateCodeFormSubmitting}
onPress={validateAndSubmitForm}
/>
<ChangeExpensifyLoginLink onPress={clearSignInData} />
</View>
<View style={[styles.mt5, styles.signInPageWelcomeTextContainer]}>
<Terms />
</View>
</>
);
}
BaseValidateCodeForm.propTypes = propTypes;
BaseValidateCodeForm.defaultProps = defaultProps;
BaseValidateCodeForm.displayName = 'BaseValidateCodeForm';
export default compose(
withLocalize,
withOnyx({
account: {key: ONYXKEYS.ACCOUNT},
credentials: {key: ONYXKEYS.CREDENTIALS},
session: {key: ONYXKEYS.SESSION},
}),
withNetwork(),
withToggleVisibilityView,
)(BaseValidateCodeForm);