Skip to content

Commit

Permalink
fix: two factor resend mail (#6044)
Browse files Browse the repository at this point in the history
Co-authored-by: Diego Mello <[email protected]>
  • Loading branch information
OtavioStasiak and diegolmello authored Dec 17, 2024
1 parent 5046239 commit a000522
Show file tree
Hide file tree
Showing 29 changed files with 78 additions and 25 deletions.
11 changes: 10 additions & 1 deletion app/containers/Button/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ const styles = StyleSheet.create({
...sharedStyles.textMedium,
...sharedStyles.textAlignCenter
},
smallText: {
...sharedStyles.textBold,
fontSize: 12,
lineHeight: 18
},
disabled: {
opacity: 0.3
}
Expand Down Expand Up @@ -75,7 +80,11 @@ const Button: React.FC<IButtonProps> = ({
style
];

const textStyle = [styles.text, { color: isDisabled ? colors.buttonPrimaryDisabled : resolvedTextColor, fontSize }, styleText];
const textStyle = [
{ color: isDisabled ? colors.buttonPrimaryDisabled : resolvedTextColor, fontSize },
small ? styles.smallText : styles.text,
styleText
];

return (
<Touchable
Expand Down
52 changes: 36 additions & 16 deletions app/containers/TwoFactor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@ import isEmpty from 'lodash/isEmpty';
import { sha256 } from 'js-sha256';
import Modal from 'react-native-modal';
import useDeepCompareEffect from 'use-deep-compare-effect';
import { connect } from 'react-redux';

import { FormTextInput } from '../TextInput';
import I18n from '../../i18n';
import EventEmitter from '../../lib/methods/helpers/events';
import { useTheme } from '../../theme';
import { themes } from '../../lib/constants';
import Button from '../Button';
import sharedStyles from '../../views/Styles';
import styles from './styles';
import { IApplicationState } from '../../definitions';
import { ICredentials } from '../../definitions';
import { Services } from '../../lib/services';
import { useAppSelector } from '../../lib/hooks';
import Toast from '../Toast';
import { showToast } from '../../lib/methods/helpers/showToast';
import log from '../../lib/methods/helpers/log';

export const TWO_FACTOR = 'TWO_FACTOR';

Expand All @@ -32,6 +34,7 @@ interface IMethods {
}

interface EventListenerMethod {
params?: ICredentials;
method?: keyof IMethods;
submit?: (param: string) => void;
cancel?: () => void;
Expand All @@ -55,15 +58,31 @@ const methods: IMethods = {
}
};

const TwoFactor = React.memo(({ isMasterDetail }: { isMasterDetail: boolean }) => {
const { theme } = useTheme();
const TwoFactor = React.memo(() => {
const { colors } = useTheme();
const { isMasterDetail } = useAppSelector(state => ({
isMasterDetail: state.app.isMasterDetail as boolean
}));
const [visible, setVisible] = useState(false);
const [data, setData] = useState<EventListenerMethod>({});
const [code, setCode] = useState<string>('');

const method = data.method ? methods[data.method] : null;
const isEmail = data.method === 'email';
const sendEmail = () => Services.sendEmailCode();
const params = data?.params;

const sendEmail = async () => {
try {
if (params?.user) {
const response = await Services.sendEmailCode(params?.user);
if (response.success) {
showToast(I18n.t('Two_Factor_Success_message'));
}
}
} catch (e) {
log(e)
}
};

useDeepCompareEffect(() => {
if (!isEmpty(data)) {
Expand Down Expand Up @@ -102,15 +121,15 @@ const TwoFactor = React.memo(({ isMasterDetail }: { isMasterDetail: boolean }) =
setData({});
};

const color = themes[theme].fontTitlesLabels;
const color = colors.fontTitlesLabels;
return (
<Modal avoidKeyboard useNativeDriver isVisible={visible} hideModalContentWhileAnimating>
<View style={styles.container} testID='two-factor'>
<View
style={[
styles.content,
isMasterDetail && [sharedStyles.modalFormSheet, styles.tablet],
{ backgroundColor: themes[theme].surfaceTint }
{ backgroundColor: colors.surfaceTint }
]}>
<Text style={[styles.title, { color }]}>{I18n.t(method?.title || 'Two_Factor_Authentication')}</Text>
{method?.text ? <Text style={[styles.subtitle, { color }]}>{I18n.t(method.text)}</Text> : null}
Expand All @@ -127,22 +146,23 @@ const TwoFactor = React.memo(({ isMasterDetail }: { isMasterDetail: boolean }) =
testID='two-factor-input'
/>
{isEmail ? (
<Text style={[styles.sendEmail, { color }]} onPress={sendEmail}>
{I18n.t('Resend_email')}
</Text>
<Button
small
title={I18n.t('Resend_email')}
style={[styles.button, { marginTop: 12 }]}
type='secondary'
onPress={sendEmail}
/>
) : null}
<View style={styles.buttonContainer}>
<Button title={I18n.t('Cancel')} type='secondary' style={styles.button} onPress={onCancel} />
<Button title={I18n.t('Verify')} type='primary' style={styles.button} onPress={onSubmit} testID='two-factor-send' />
</View>
</View>
<Toast />
</View>
</Modal>
);
});

const mapStateToProps = (state: IApplicationState) => ({
isMasterDetail: state.app.isMasterDetail
});

export default connect(mapStateToProps)(TwoFactor);
export default TwoFactor;
1 change: 1 addition & 0 deletions app/i18n/locales/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@
"Translate": "ترجمة",
"Try_again": "حاول مجدداً",
"Two_Factor_Authentication": "المصادقة الثنائية",
"Two_Factor_Success_message": "تم إرسال رمز التحقق الثنائي العوامل! يرجى التحقق من بريدك الإلكتروني.",
"Type_message": "اكتب رسالة",
"UNARCHIVE": "إلغاء الأرشفة",
"unarchive": "إلغاء الأرشفة",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/bn-IN.json
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,7 @@
"Translate": "অনুবাদ করুন",
"Try_again": "আবার চেষ্টা করুন",
"Two_Factor_Authentication": "দুটি ধারণামূলক প্রমাণীকরণ",
"Two_Factor_Success_message": "দুই-স্তরের প্রমাণীকরণ কোড পাঠানো হয়েছে! অনুগ্রহ করে আপনার ইমেইল চেক করুন।",
"Type_message": "বার্তা লিখুন",
"Types": "ধরণ",
"UNARCHIVE": "আনআরকাইভ",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,7 @@
"Troubleshooting": "Odstraňování problémů",
"Try_again": "Zkusit to znovu",
"Two_Factor_Authentication": "Dvoufaktorové ověřování",
"Two_Factor_Success_message": "Byl odeslán dvoufaktorový autentizační kód! Zkontrolujte svůj e-mail.",
"Type_message": "Zadejte zprávu",
"Types": "Typy",
"UNARCHIVE": "UNARCHIVOVAT",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,7 @@
"Translate": "Übersetzen",
"Try_again": "Versuchen Sie es nochmal",
"Two_Factor_Authentication": "Zwei-Faktor-Authentifizierung",
"Two_Factor_Success_message": "Zwei-Faktor-Authentifizierungscode gesendet! Bitte überprüfen Sie Ihre E-Mail.",
"Type_message": "Nachricht schreiben",
"Types": "Typen",
"UNARCHIVE": "WIEDERHERSTELLEN",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,7 @@
"Troubleshooting": "Troubleshooting",
"Try_again": "Try again",
"Two_Factor_Authentication": "Two-factor authentication",
"Two_Factor_Success_message": "Two-factor authentication code sent! Please check your email.",
"Type_message": "Type message",
"Types": "Types",
"UNARCHIVE": "UNARCHIVE",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@
"Translate": "Traducir",
"Try_again": "Intentar de nuevo",
"Two_Factor_Authentication": "Autenticación de doble factor",
"Two_Factor_Success_message": "¡Código de autenticación de dos factores enviado! Por favor, revisa tu correo electrónico.",
"Type_message": "Escribir mensaje",
"UNARCHIVE": "DESARCHIVAR",
"unarchive": "desarchivar",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,7 @@
"Translate": "Käännä",
"Try_again": "Yritä uudelleen",
"Two_Factor_Authentication": "Kaksivaiheinen tunnistautuminen",
"Two_Factor_Success_message": "Kaksivaiheinen todennuskoodi lähetetty! Tarkista sähköpostisi.",
"Type_message": "Kirjoita viesti",
"Types": "Tyypit",
"UNARCHIVE": "PALAUTA ARKISTOSTA",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@
"Translate": "Traduire",
"Try_again": "Réessayer",
"Two_Factor_Authentication": "Authentification à deux facteurs",
"Two_Factor_Success_message": "Code d'authentification à deux facteurs envoyé ! Veuillez vérifier votre e-mail.",
"Type_message": "Tapez le message",
"Types": "Types",
"UNARCHIVE": "DÉSARCHIVER",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/hi-IN.json
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,7 @@
"Translate": "अनुवाद करें",
"Try_again": "फिर कोशिश करें",
"Two_Factor_Authentication": "दो-क्रमिक प्रमाणीकरण",
"Two_Factor_Success_message": "दो-कारक प्रमाणीकरण कोड भेजा गया! कृपया अपना ईमेल चेक करें।",
"Type_message": "संदेश टाइप करें",
"Types": "प्रकार",
"UNARCHIVE": "अनारकाइव करें",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/hu.json
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,7 @@
"Translate": "Fordítás",
"Try_again": "Próbálja újra",
"Two_Factor_Authentication": "Kétfaktoros hitelesítés",
"Two_Factor_Success_message": "Kétfaktoros hitelesítési kód elküldve! Kérjük, ellenőrizze az emailjét.",
"Type_message": "Üzenet típusa",
"Types": "Típusok",
"UNARCHIVE": "ARCHIVÁLÁS MEGSZÜNTETÉS",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@
"Translate": "Traduci",
"Try_again": "Riprova",
"Two_Factor_Authentication": "Autenticazione a due fattori",
"Two_Factor_Success_message": "Codice di autenticazione a due fattori inviato! Si prega di controllare la tua email.",
"Type_message": "Scrivi messaggio",
"UNARCHIVE": "RIMUOVI DALL'ARCHIVIO",
"unarchive": "rimuovi dall'archivio",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@
"Translate": "翻訳",
"Try_again": "再度お試しください。",
"Two_Factor_Authentication": "2段階認証",
"Two_Factor_Success_message": "二要素認証コードが送信されました!メールを確認してください。",
"Type_message": "メッセージを入力",
"UNARCHIVE": "アーカイブ解除",
"unarchive": "アーカイブ解除",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@
"Translate": "Vertalen",
"Try_again": "Probeer het opnieuw",
"Two_Factor_Authentication": "Twee-factor authenticatie",
"Two_Factor_Success_message": "Twee-factor authenticatiecode verzonden! Controleer uw e-mail.",
"Type_message": "Typ bericht",
"Types": "Soorten",
"UNARCHIVE": "DEARCHIVEREN",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@
"Translate": "Traduzir",
"Try_again": "Tentar novamente",
"Two_Factor_Authentication": "Autenticação de dois fatores",
"Two_Factor_Success_message": "Código de autenticação de dois fatores enviado! Por favor, verifique seu e-mail.",
"Type_message": "Digitar mensagem",
"Types": "Tipos",
"UNARCHIVE": "DESARQUIVAR",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/pt-PT.json
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@
"topic": "tópico",
"Try_again": "Tente novamente",
"Two_Factor_Authentication": "Autenticação 2FA",
"Two_Factor_Success_message": "Código de autenticação de dois fatores enviado! Por favor, verifique o seu email.",
"UNARCHIVE": "DESARQUIVAR",
"unarchive": "desarquivar",
"Unmute": "Retirar silêncio",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,7 @@
"Translate": "Перевести",
"Try_again": "Попробуйте еще раз",
"Two_Factor_Authentication": "Двухфакторная аутентификация",
"Two_Factor_Success_message": "Код двухфакторной аутентификации отправлен! Пожалуйста, проверьте вашу электронную почту.",
"Type_message": "Написать сообщение",
"Types": "Типы",
"UNARCHIVE": "РАЗАРХИВИРОВАТЬ",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/sl-SI.json
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@
"Translate": "Prevesti",
"Try_again": "Poskusi ponovno",
"Two_Factor_Authentication": "Dvofaktorska overjanje",
"Two_Factor_Success_message": "Dvofaktorska avtentikacijska koda poslana! Prosimo, preverite svoj e-poštni naslov.",
"Type_message": "Tip sporočila",
"Types": "Vrste",
"UNARCHIVE": "ODPAKIRATI",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,7 @@
"Translate": "Översätt",
"Try_again": "Försök igen",
"Two_Factor_Authentication": "Tvåfaktorsautentisering",
"Two_Factor_Success_message": "Tvåfaktorsautentiseringskod skickad! Vänligen kontrollera din e-post.",
"Type_message": "Skriv meddelande",
"Types": "Typer",
"UNARCHIVE": "AVARKIVERA",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/ta-IN.json
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,7 @@
"Translate": "மொழிபெயர்",
"Try_again": "மீண்டும் முயற்சி செய்",
"Two_Factor_Authentication": "இரண்டு பரிமாறு அங்கீகாரம்",
"Two_Factor_Success_message": "இரண்டு காரணி உறுதிப்படுத்தல் குறியீடு அனுப்பப்பட்டுள்ளது! உங்கள் மின்னஞ்சலை சரிபார்க்கவும்.",
"Type_message": "செய்தியை தட்டச்சு",
"Types": "வகைகள்",
"UNARCHIVE": "அசைவு செய்",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/te-IN.json
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,7 @@
"Translate": "అనువాదం",
"Try_again": "ప్రయత్నించండి",
"Two_Factor_Authentication": "రెండు అంశ ప్రామాణీకరణ",
"Two_Factor_Success_message": "द्वि-घटक प्रमाणीकरण कोड भेज दिया गया है! कृपया अपना ईमेल जाँचें।",
"Type_message": "సందేశాన్ని టైప్ చేయండి",
"Types": "రకాలు",
"UNARCHIVE": "అనార్కైవ్",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,7 @@
"Translate": "Çevir",
"Try_again": "Tekrar deneyin",
"Two_Factor_Authentication": "İki faktörlü Kimlik Doğrulama",
"Two_Factor_Success_message": "İki faktörlü kimlik doğrulama kodu gönderildi! Lütfen e-postanızı kontrol edin.",
"Type_message": "İleti yaz",
"UNARCHIVE": "ARŞİVDEN ÇIKAR",
"unarchive": "arşivden çıkar",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,7 @@
"Translate": "翻译",
"Try_again": "再试一次",
"Two_Factor_Authentication": "双重认证",
"Two_Factor_Success_message": "已发送双因素验证代码!请检查您的电子邮件。",
"Type_message": "输入信息",
"UNARCHIVE": "取消封存",
"unarchive": "取消封存",
Expand Down
1 change: 1 addition & 0 deletions app/i18n/locales/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,7 @@
"Translate": "翻譯",
"Try_again": "再試一次",
"Two_Factor_Authentication": "雙重認證",
"Two_Factor_Success_message": "雙重驗證碼已發送!請檢查您的電子郵件。",
"Type_message": "輸入訊息",
"UNARCHIVE": "取消封存",
"unarchive": "取消封存",
Expand Down
2 changes: 2 additions & 0 deletions app/lib/methods/helpers/events.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ICredentials } from '../../../definitions';
import { IEmitUserInteraction } from '../../../containers/UIKit/interfaces';
import log from './log';

Expand All @@ -12,6 +13,7 @@ type TEventEmitterEmmitArgs =
| { visible: boolean; onCancel?: null | Function }
| { cancel: () => void }
| { submit: (param: string) => void }
| { params: ICredentials }
| IEmitUserInteraction;

class EventEmitter {
Expand Down
2 changes: 1 addition & 1 deletion app/lib/services/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ function loginTOTP(params: ICredentials, loginEmailPassword?: boolean, isFromWeb
if (e.data?.error && (e.data.error === 'totp-required' || e.data.error === 'totp-invalid')) {
const { details } = e.data;
try {
const code = await twoFactor({ method: details?.method || 'totp', invalid: details?.error === 'totp-invalid' });
const code = await twoFactor({ params, method: details?.method || 'totp', invalid: details?.error === 'totp-invalid' });

if (loginEmailPassword) {
store.dispatch(setUser({ username: params.user || params.username }));
Expand Down
8 changes: 2 additions & 6 deletions app/lib/services/restApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
IRoom,
IRoomNotifications,
IServerRoom,
IUser,
RoomType,
SubscriptionType
} from '../../definitions';
Expand Down Expand Up @@ -984,11 +983,8 @@ export const pushTest = () => sdk.post('push.test');
// RC 6.5.0
export const pushInfo = () => sdk.get('push.info');

export const sendEmailCode = () => {
const { username } = reduxStore.getState().login.user as IUser;
// RC 3.1.0
return sdk.post('users.2fa.sendEmailCode', { emailOrUsername: username });
};
// RC 3.1.0
export const sendEmailCode = (emailOrUsername: string) => sdk.post('users.2fa.sendEmailCode', { emailOrUsername });

export const getRoomMembers = async ({
rid,
Expand Down
5 changes: 4 additions & 1 deletion app/lib/services/twoFactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ import { settings } from '@rocket.chat/sdk';

import { TWO_FACTOR } from '../../containers/TwoFactor';
import EventEmitter from '../methods/helpers/events';
import { ICredentials } from '../../definitions';

interface ITwoFactor {
method: string;
invalid: boolean;
params?: ICredentials;
}

export const twoFactor = ({ method, invalid }: ITwoFactor): Promise<{ twoFactorCode: string; twoFactorMethod: string }> =>
export const twoFactor = ({ method, invalid, params }: ITwoFactor): Promise<{ twoFactorCode: string; twoFactorMethod: string }> =>
new Promise((resolve, reject) => {
EventEmitter.emit(TWO_FACTOR, {
method,
invalid,
params,
cancel: () => reject(),
submit: (code: string) => {
settings.customHeaders = {
Expand Down

0 comments on commit a000522

Please sign in to comment.