Skip to content
Closed
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
32 changes: 32 additions & 0 deletions app/containers/TwoFactor/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,36 @@ describe('TwoFactor', () => {

await expect(newest!).resolves.toEqual({ twoFactorCode: '123456', twoFactorMethod: 'totp' });
});

it('rejects the pending request when the presenter is removed', async () => {
const { getByTestId, unmount } = render(<TwoFactor />);

let pending: Promise<unknown> | undefined;
await act(() => {
pending = requestTwoFactor().catch(error => error);
});

await waitFor(() => expect(getByTestId('two-factor-input')).toBeTruthy());

unmount();

expect(isTwoFactorCancelled(await pending!)).toBe(true);
});

it('rejects the pending request when Cancel is pressed', async () => {
const { getByTestId, getByText } = render(<TwoFactor />);

let pending: Promise<unknown> | undefined;
await act(() => {
pending = requestTwoFactor().catch(error => error);
});

await waitFor(() => expect(getByTestId('two-factor-input')).toBeTruthy());

await act(() => {
fireEvent.press(getByText('Cancel'));
});

expect(isTwoFactorCancelled(await pending!)).toBe(true);
});
});
44 changes: 9 additions & 35 deletions app/containers/TwoFactor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, memo } from 'react';
import { useEffect, useState, memo } from 'react';
import { AccessibilityInfo, Text, View } from 'react-native';
import isEmpty from 'lodash/isEmpty';
import { sha256 } from 'js-sha256';
Expand All @@ -11,40 +11,24 @@ import { GestureHandlerRootView } from 'react-native-gesture-handler';

import { ControlledFormTextInput } from '../TextInput';
import I18n from '../../i18n';
import EventEmitter from '../../lib/methods/helpers/events';
import { useTheme } from '../../theme';
import Button from '../Button';
import sharedStyles from '../../views/Styles';
import styles from './styles';
import { type ILoginCredentials } from '../../definitions';
import { sendEmailCode } from '../../lib/services/restApi';
import { useMasterDetail } from '../../lib/hooks/useMasterDetail';
import Toast from '../Toast';
import { showToast } from '../../lib/methods/helpers/showToast';
import log from '../../lib/methods/helpers/log';
import { TWO_FACTOR } from '../../lib/constants/twoFactor';
import { cancelActiveRequest, type ITwoFactorPrompt, subscribeToTwoFactorPrompts } from '../../lib/services/twoFactor/twoFactor';

interface IMethodsProp {
text: string;
keyboardType: 'numeric' | 'default';
title?: string;
secureTextEntry?: boolean;
}
interface IMethods {
totp: IMethodsProp;
email: IMethodsProp;
password: IMethodsProp;
}

interface EventListenerMethod {
params?: ILoginCredentials;
method?: keyof IMethods;
submit?: (param: string) => void;
cancel?: () => void;
invalid?: boolean;
}

const methods: IMethods = {
const methods: Record<string, IMethodsProp> = {
totp: {
text: 'Open_your_authentication_app_and_enter_the_code',
keyboardType: 'numeric'
Expand All @@ -68,8 +52,7 @@ const TwoFactor = memo(() => {
const { colors } = useTheme();
const isMasterDetail = useMasterDetail();
const [visible, setVisible] = useState(false);
const [data, setData] = useState<EventListenerMethod>({});
const pendingCancel = useRef<EventListenerMethod['cancel']>(undefined);
const [data, setData] = useState<Partial<ITwoFactorPrompt>>({});
const {
control,
setValue,
Expand Down Expand Up @@ -113,41 +96,32 @@ const TwoFactor = memo(() => {
}
}, [data]);

const showTwoFactor = (args: EventListenerMethod) => {
pendingCancel.current?.();
pendingCancel.current = args.cancel;
const showTwoFactor = (args: ITwoFactorPrompt) => {
setData(args);
if (args.invalid) {
setError('code', { message: I18n.t('Invalid_code'), type: 'validate' });
AccessibilityInfo.announceForAccessibility(I18n.t('Invalid_code'));
}
};

useEffect(() => {
const listener = EventEmitter.addEventListener(TWO_FACTOR, showTwoFactor);

return () => EventEmitter.removeListener(TWO_FACTOR, listener);
}, []);
useEffect(() => subscribeToTwoFactorPrompts(showTwoFactor), []);

const onCancel = () => {
const { cancel } = data;
pendingCancel.current = undefined;
if (cancel) {
cancel();
}
cancelActiveRequest();
setData({});
};

const onSubmit = () => {
const { submit } = data;
pendingCancel.current = undefined;
if (submit) {
const { code } = getValues();
if (data.method === 'password') {
submit(sha256(code));
} else {
submit(code);
}
} else {
cancelActiveRequest();
}
clearErrors();
setData({});
Expand Down
37 changes: 17 additions & 20 deletions app/lib/methods/helpers/handleSaveUserProfileError.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import I18n from '../../../i18n';
import { showErrorAlert } from '.';
import { isTwoFactorCancelled } from '../../services/twoFactor/twoFactorCancelled';
import { presentUnlessCancelled, showErrorAlert } from '.';

const handleSaveUserProfileError = (e: any, action: string) => {
if (isTwoFactorCancelled(e)) {
return;
}
if (e.data && e.data.error.includes('[error-too-many-requests]')) {
return showErrorAlert(e.data.error);
}
if (I18n.isTranslated(e.error)) {
return showErrorAlert(I18n.t(e.error));
}
let msg = I18n.t('There_was_an_error_while_action', { action: I18n.t(action) });
let title = '';
if (typeof e.reason === 'string') {
title = msg;
msg = e.reason;
}
showErrorAlert(msg, title);
};
const handleSaveUserProfileError = (e: any, action: string) =>
presentUnlessCancelled(e, () => {
if (e.data && e.data.error.includes('[error-too-many-requests]')) {
return showErrorAlert(e.data.error);
}
if (I18n.isTranslated(e.error)) {
return showErrorAlert(I18n.t(e.error));
}
let msg = I18n.t('There_was_an_error_while_action', { action: I18n.t(action) });
let title = '';
if (typeof e.reason === 'string') {
title = msg;
msg = e.reason;
}
showErrorAlert(msg, title);
});

export default handleSaveUserProfileError;
25 changes: 15 additions & 10 deletions app/lib/methods/helpers/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,26 @@ import { isTwoFactorCancelled } from '../../services/twoFactor/twoFactorCancelle
export const showErrorAlert = (message: string, title?: string, onPress = () => {}): void =>
Alert.alert(title || '', message, [{ text: 'OK', onPress }], { cancelable: true });

export const showErrorAlertWithEMessage = (e: any, title?: string): void => {
export const presentUnlessCancelled = (e: unknown, present: () => void): void => {
if (isTwoFactorCancelled(e)) {
return;
}
let errorMessage: string = e?.data?.error;
present();
};

if (errorMessage?.includes('[error-too-many-requests]')) {
const seconds = errorMessage.replace(/\D/g, '');
errorMessage = I18n.t('error-too-many-requests', { seconds });
} else {
errorMessage = I18n.isTranslated(errorMessage) ? I18n.t(errorMessage) : errorMessage;
}
export const showErrorAlertWithEMessage = (e: any, title?: string): void =>
presentUnlessCancelled(e, () => {
let errorMessage: string = e?.data?.error;

showErrorAlert(errorMessage, title);
};
if (errorMessage?.includes('[error-too-many-requests]')) {
const seconds = errorMessage.replace(/\D/g, '');
errorMessage = I18n.t('error-too-many-requests', { seconds });
} else {
errorMessage = I18n.isTranslated(errorMessage) ? I18n.t(errorMessage) : errorMessage;
}

showErrorAlert(errorMessage, title);
});

interface IShowConfirmationAlert {
title?: string;
Expand Down
Loading
Loading