Skip to content
Merged
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
111 changes: 69 additions & 42 deletions src/libs/Authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import redirectToSignIn from './actions/SignInRedirect';
import {getAuthenticateErrorMessage} from './ErrorUtils';
import Log from './Log';
import {post} from './Network';
import {getCredentials, setAuthToken, setIsAuthenticating} from './Network/NetworkStore';
import {getCredentials, hasReadRequiredDataFromStorage, setAuthToken, setIsAuthenticating} from './Network/NetworkStore';
import requireParameters from './requireParameters';

type Parameters = {
Expand Down Expand Up @@ -71,58 +71,85 @@ function Authenticate(parameters: Parameters): Promise<Response> | undefined {
* @param [command] command name for logging purposes
*/
function reauthenticate(command = ''): Promise<void> | undefined {
Log.hmmm('Reauthenticate - Attempting re-authentication', {
command,
});

// Prevent re-authentication if authentication with shortLiveToken is in progress
if (isAuthenticatingWithShortLivedToken) {
Log.hmmm('Reauthenticate - Authentication with shortLiveToken is in progress. Re-authentication aborted.', {
command,
});
return;
}

// Prevent any more requests from being processed while authentication happens
setIsAuthenticating(true);

const credentials = getCredentials();
return Authenticate({
useExpensifyLogin: false,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
partnerUserID: credentials?.autoGeneratedLogin,
partnerUserSecret: credentials?.autoGeneratedPassword,
})?.then((response) => {
if (response.jsonCode === CONST.JSON_CODE.UNABLE_TO_RETRY) {
// 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 retry reauthenticate when they come back online. Error so it can be handled by the retry mechanism.
throw new Error('Unable to retry Authenticate request');
}

// If authentication fails and we are online then log the user out
if (response.jsonCode !== 200) {
const errorMessage = getAuthenticateErrorMessage(response);
Log.hmmm('Reauthenticate - Waiting for credentials', {
command,
});

// We need to wait for credentials to be loaded from Onyx store
return hasReadRequiredDataFromStorage().then(() => {
const credentials = getCredentials();

Log.hmmm('Reauthenticate - Starting authentication process', {
command,
});

return Authenticate({
useExpensifyLogin: false,
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
partnerUserID: credentials?.autoGeneratedLogin,
partnerUserSecret: credentials?.autoGeneratedPassword,
})?.then((response) => {
Log.hmmm('Reauthenticate - Processing authentication result', {
command,
});

if (response.jsonCode === CONST.JSON_CODE.UNABLE_TO_RETRY) {
// 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 retry reauthenticate when they come back online. Error so it can be handled by the retry mechanism.
throw new Error('Unable to retry Authenticate request');
}

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

// If we reauthenticate due to an expired delegate token, restore the delegate's original account.
// This is because the credentials used to reauthenticate were for the delegate's original account, and not for the account they were connected as.
if (isConnectedAsDelegate()) {
Log.info('Reauthenticate while connected as a delegate. Restoring original account.');
restoreDelegateSession(response);
return;
}

// 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.
setAuthToken(response.authToken ?? null);

// The authentication process is finished so the network can be unpaused to continue processing requests
setIsAuthenticating(false);
Log.hmmm('Redirecting to Sign In because we failed to reauthenticate', {

Log.hmmm('Reauthenticate - Re-authentication successful', {
command,
error: errorMessage,
});
redirectToSignIn(errorMessage);
return;
}

// If we reauthenticate due to an expired delegate token, restore the delegate's original account.
// This is because the credentials used to reauthenticate were for the delegate's original account, and not for the account they were connected as.
if (isConnectedAsDelegate()) {
Log.info('Reauthenticate while connected as a delegate. Restoring original account.');
restoreDelegateSession(response);
return;
}

// 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.
setAuthToken(response.authToken ?? null);

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

Expand Down