Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[No QA] Cleanup Authentication error handling #8865

Merged
merged 5 commits into from
May 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/CONST.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,10 +313,10 @@ const CONST = {
SUCCESS: 200,
NOT_AUTHENTICATED: 407,
EXP_ERROR: 666,
UNABLE_TO_RETRY: 'unableToRetry',
},
ERROR: {
XHR_FAILED: 'xhrFailed',
API_OFFLINE: 'session.offlineMessageRetry',
UNKNOWN_ERROR: 'Unknown error',
REQUEST_CANCELLED: 'AbortError',
FAILED_TO_FETCH: 'Failed to fetch',
Expand Down
82 changes: 23 additions & 59 deletions src/libs/Authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import CONFIG from '../CONFIG';
import redirectToSignIn from './actions/SignInRedirect';
import CONST from '../CONST';
import Log from './Log';
import * as ErrorUtils from './ErrorUtils';

/**
* @param {Object} parameters
Expand Down Expand Up @@ -47,39 +48,7 @@ function Authenticate(parameters) {

// Add email param so the first Authenticate request is logged on the server w/ this email
email: parameters.email,
})
.then((response) => {
// If we didn't get a 200 response from Authenticate we either failed to Authenticate with
// an expensify login or the login credentials we created after the initial authentication.
// In both cases, we need the user to sign in again with their expensify credentials
if (response.jsonCode !== 200) {
switch (response.jsonCode) {
case 401:
throw new Error('passwordForm.error.incorrectLoginOrPassword');
case 402:
// If too few characters are passed as the password, the WAF will pass it to the API as an empty
// string, which results in a 402 error from Auth.
if (response.message === '402 Missing partnerUserSecret') {
throw new Error('passwordForm.error.incorrectLoginOrPassword');
}
throw new Error('passwordForm.error.twoFactorAuthenticationEnabled');
case 403:
if (response.message === 'Invalid code') {
throw new Error('passwordForm.error.incorrect2fa');
}
throw new Error('passwordForm.error.invalidLoginOrPassword');
case 404:
throw new Error('passwordForm.error.unableToResetPassword');
case 405:
throw new Error('passwordForm.error.noAccess');
case 413:
throw new Error('passwordForm.error.accountLocked');
default:
throw new Error('passwordForm.error.fallback');
}
}
return response;
});
});
}

/**
Expand All @@ -101,43 +70,38 @@ function reauthenticate(command = '') {
partnerUserSecret: credentials.autoGeneratedPassword,
})
.then((response) => {
// If authentication fails throw so that we hit
// the catch below and redirect to sign in
if (response.jsonCode === CONST.JSON_CODE.UNABLE_TO_RETRY) {
// If authentication fails, then the network can be unpaused
NetworkStore.setIsAuthenticating(false);

// When a fetch() fails due to a network issue and an error is thrown we won't log the user out. Most likely they
// have a spotty connection and will need to try to reauthenticate when they come back online. We will error so it
// can be handled by callers of reauthenticate().
throw new Error('Unable to retry Authenticate request');
}

// If authentication fails and we are online then log the user out
if (response.jsonCode !== 200) {
throw new Error(response.message);
const errorMessage = ErrorUtils.getAuthenticateErrorMessage(response);
NetworkStore.setIsAuthenticating(false);
Log.hmmm('Redirecting to Sign In because we failed to reauthenticate', {
command,
error: errorMessage,
});
redirectToSignIn(errorMessage);
return;
}

// Update authToken in Onyx and in our local variables so that API requests will use the
// new authToken
// Update authToken in Onyx and in our local variables so that API requests will use the new authToken
updateSessionAuthTokens(response.authToken, response.encryptedAuthToken);

// Note: It is important to manually set the authToken that is in the store here since any requests that are hooked into
// reauthenticate .then() will immediate post and use the local authToken. Onyx updates subscribers lately so it is not
// enough to do the updateSessionAuthTokens() call above.
NetworkStore.setAuthToken(response.authToken);

// The authentication process is finished so the network can be unpaused to continue
// processing requests
NetworkStore.setIsAuthenticating(false);
})

.catch((error) => {
// If authentication fails, then the network can be unpaused
// The authentication process is finished so the network can be unpaused to continue processing requests
NetworkStore.setIsAuthenticating(false);

// When a fetch() fails and the "API is offline" error is thrown we won't log the user out. Most likely they
// have a spotty connection and will need to try to reauthenticate when they come back online. We will
// re-throw this error so it can be handled by callers of reauthenticate().
if (error.message === CONST.ERROR.API_OFFLINE) {
throw error;
}

// If we experience something other than a network error then redirect the user to sign in
Log.hmmm('Redirecting to Sign In because we failed to reauthenticate', {
command,
error: error.message,
});
redirectToSignIn(error.message);
});
}

Expand Down
41 changes: 41 additions & 0 deletions src/libs/ErrorUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import CONST from '../CONST';

/**
* @param {Object} response
* @param {Number} response.jsonCode
* @param {String} response.message
* @returns {String}
*/
function getAuthenticateErrorMessage(response) {
switch (response.jsonCode) {
case CONST.JSON_CODE.UNABLE_TO_RETRY:
return 'session.offlineMessageRetry';
case 401:
return 'passwordForm.error.incorrectLoginOrPassword';
case 402:
// If too few characters are passed as the password, the WAF will pass it to the API as an empty
// string, which results in a 402 error from Auth.
if (response.message === '402 Missing partnerUserSecret') {
return 'passwordForm.error.incorrectLoginOrPassword';
}
return 'passwordForm.error.twoFactorAuthenticationEnabled';
case 403:
if (response.message === 'Invalid code') {
return 'passwordForm.error.incorrect2fa';
}
return 'passwordForm.error.invalidLoginOrPassword';
case 404:
return 'passwordForm.error.unableToResetPassword';
case 405:
return 'passwordForm.error.noAccess';
case 413:
return 'passwordForm.error.accountLocked';
default:
return 'passwordForm.error.fallback';
}
}

export {
// eslint-disable-next-line import/prefer-default-export
getAuthenticateErrorMessage,
};
2 changes: 1 addition & 1 deletion src/libs/Middleware/Retry.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function Retry(response, request, isFromSequentialQueue) {
console.debug('[Network] There was an error in the Log API command, unable to log to server!', error);
}

request.reject(new Error(CONST.ERROR.API_OFFLINE));
request.resolve({jsonCode: CONST.JSON_CODE.UNABLE_TO_RETRY});
});
}

Expand Down
28 changes: 19 additions & 9 deletions src/libs/actions/Report.js
Original file line number Diff line number Diff line change
Expand Up @@ -1420,7 +1420,11 @@ function editReportComment(reportID, originalReportAction, textForNewComment) {
reportComment: htmlForNewComment,
sequenceNumber,
})
.catch(() => {
.then((response) => {
if (response.jsonCode === 200) {
return;
}

// If it fails, reset Onyx
actionToMerge[sequenceNumber] = originalReportAction;
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, actionToMerge);
Expand Down Expand Up @@ -1515,10 +1519,16 @@ function createPolicyRoom(policyID, reportName, visibility) {
Onyx.set(ONYXKEYS.IS_LOADING_CREATE_POLICY_ROOM, true);
return API.CreatePolicyRoom({policyID, reportName, visibility})
.then((response) => {
if (response.jsonCode !== 200) {
if (response.jsonCode === CONST.JSON_CODE.UNABLE_TO_RETRY) {
Growl.error(Localize.translateLocal('newRoomPage.growlMessageOnError'));
return;
}

if (response.jsonCode !== CONST.JSON_CODE.SUCCESS) {
Growl.error(response.message);
return;
}

return fetchChatReportsByIDs([response.reportID]);
})
.then((chatReports) => {
Expand All @@ -1529,9 +1539,6 @@ function createPolicyRoom(policyID, reportName, visibility) {
}
Navigation.navigate(ROUTES.getReportRoute(reportID));
})
.catch(() => {
Growl.error(Localize.translateLocal('newRoomPage.growlMessageOnError'));
})
.finally(() => Onyx.set(ONYXKEYS.IS_LOADING_CREATE_POLICY_ROOM, false));
}

Expand All @@ -1544,18 +1551,21 @@ function renameReport(reportID, reportName) {
Onyx.set(ONYXKEYS.IS_LOADING_RENAME_POLICY_ROOM, true);
API.RenameReport({reportID, reportName})
.then((response) => {
if (response.jsonCode !== 200) {
if (response.jsonCode === CONST.JSON_CODE.UNABLE_TO_RETRY) {
Growl.error(Localize.translateLocal('newRoomPage.growlMessageOnRenameError'));
return;
}

if (response.jsonCode !== CONST.JSON_CODE.SUCCESS) {
Growl.error(response.message);
return;
}

Growl.success(Localize.translateLocal('newRoomPage.policyRoomRenamed'));

// Update the report name so that the LHN and header display the updated name
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {reportName});
})
.catch(() => {
Growl.error(Localize.translateLocal('newRoomPage.growlMessageOnRenameError'));
})
.finally(() => Onyx.set(ONYXKEYS.IS_LOADING_RENAME_POLICY_ROOM, false));
}

Expand Down
46 changes: 30 additions & 16 deletions src/libs/actions/Session/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import NetworkConnection from '../../NetworkConnection';
import * as User from '../User';
import * as ValidationUtils from '../../ValidationUtils';
import * as Authentication from '../../Authentication';
import * as ErrorUtils from '../../ErrorUtils';
import * as Welcome from '../Welcome';

let credentials = {};
Expand Down Expand Up @@ -79,7 +80,13 @@ function signOut() {
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
shouldRetry: false,
})
.catch(error => Onyx.merge(ONYXKEYS.SESSION, {error: error.message}));
.then((response) => {
if (response.jsonCode === CONST.JSON_CODE.SUCCESS) {
return;
}

Onyx.merge(ONYXKEYS.SESSION, {error: response.message});
});
}
Onyx.set(ONYXKEYS.SESSION, null);
Onyx.set(ONYXKEYS.CREDENTIALS, null);
Expand Down Expand Up @@ -153,13 +160,12 @@ function fetchAccountDetails(login) {
? Localize.translateLocal('messages.errorMessageInvalidPhone')
: Localize.translateLocal('loginForm.error.invalidFormatEmailLogin'),
});
} else if (response.jsonCode === CONST.JSON_CODE.UNABLE_TO_RETRY) {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: Localize.translateLocal('session.offlineMessageRetry')});
} else {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: response.message});
}
})
.catch(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: Localize.translateLocal('session.offlineMessageRetry')});
})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
Expand Down Expand Up @@ -191,7 +197,8 @@ function createTemporaryLogin(authToken, email) {
})
.then((createLoginResponse) => {
if (createLoginResponse.jsonCode !== 200) {
throw new Error(createLoginResponse.message);
Onyx.merge(ONYXKEYS.ACCOUNT, {error: createLoginResponse.message});
return;
}

setSuccessfulSignInData(createLoginResponse);
Expand All @@ -205,7 +212,13 @@ function createTemporaryLogin(authToken, email) {
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
shouldRetry: false,
})
.catch(Log.info);
.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, {
Expand All @@ -214,9 +227,6 @@ function createTemporaryLogin(authToken, email) {
});
return createLoginResponse;
})
.catch((error) => {
Onyx.merge(ONYXKEYS.ACCOUNT, {error: error.message});
})
.finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {loading: false});
});
Expand All @@ -242,15 +252,19 @@ function signIn(password, twoFactorAuthCode) {
twoFactorAuthCode,
email: credentials.login,
})
.then(({authToken, email}) => {
createTemporaryLogin(authToken, email);
})
.catch((error) => {
if (error.message === 'passwordForm.error.twoFactorAuthenticationEnabled') {
Onyx.merge(ONYXKEYS.ACCOUNT, {requiresTwoFactorAuth: true, loading: false});
.then((response) => {
if (response.jsonCode !== 200) {
const errorMessage = ErrorUtils.getAuthenticateErrorMessage(response);
if (errorMessage === 'passwordForm.error.twoFactorAuthenticationEnabled') {
Onyx.merge(ONYXKEYS.ACCOUNT, {requiresTwoFactorAuth: true, loading: false});
return;
}
Onyx.merge(ONYXKEYS.ACCOUNT, {error: Localize.translateLocal(errorMessage), loading: false});
return;
}
Onyx.merge(ONYXKEYS.ACCOUNT, {error: Localize.translateLocal(error.message), loading: false});

const {authToken, email} = response;
createTemporaryLogin(authToken, email);
});
}

Expand Down
22 changes: 13 additions & 9 deletions src/libs/actions/Wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,19 @@ function fetchOnfidoToken(firstName, lastName, dob) {
Onyx.set(ONYXKEYS.WALLET_ONFIDO, {loading: true});
API.Wallet_GetOnfidoSDKToken(firstName, lastName, dob)
.then((response) => {
const apiResult = lodashGet(response, ['requestorIdentityOnfido', 'apiResult'], {});
Onyx.merge(ONYXKEYS.WALLET_ONFIDO, {
applicantID: apiResult.applicantID,
sdkToken: apiResult.sdkToken,
loading: false,
hasAcceptedPrivacyPolicy: true,
});
})
.catch(() => Onyx.set(ONYXKEYS.WALLET_ONFIDO, {loading: false, error: CONST.WALLET.ERROR.UNEXPECTED}));
if (response.jsonCode === CONST.JSON_CODE.SUCCESS) {
const apiResult = lodashGet(response, ['requestorIdentityOnfido', 'apiResult'], {});
Onyx.merge(ONYXKEYS.WALLET_ONFIDO, {
applicantID: apiResult.applicantID,
sdkToken: apiResult.sdkToken,
loading: false,
hasAcceptedPrivacyPolicy: true,
});
return;
}

Onyx.set(ONYXKEYS.WALLET_ONFIDO, {loading: false, error: CONST.WALLET.ERROR.UNEXPECTED});
});
}

/**
Expand Down
Loading