diff --git a/res/css/_components.pcss b/res/css/_components.pcss index 5e290e1375..67c07b5d97 100644 --- a/res/css/_components.pcss +++ b/res/css/_components.pcss @@ -49,6 +49,7 @@ @import "./structures/_BackdropPanel.pcss"; @import "./structures/_CompatibilityPage.pcss"; @import "./structures/_ContextualMenu.pcss"; +@import "./structures/_ErrorMessage.pcss"; @import "./structures/_FileDropTarget.pcss"; @import "./structures/_FilePanel.pcss"; @import "./structures/_GenericDropdownMenu.pcss"; @@ -157,6 +158,7 @@ @import "./views/dialogs/_UntrustedDeviceDialog.pcss"; @import "./views/dialogs/_UploadConfirmDialog.pcss"; @import "./views/dialogs/_UserSettingsDialog.pcss"; +@import "./views/dialogs/_VerifyEMailDialog.pcss"; @import "./views/dialogs/_WidgetCapabilitiesPromptDialog.pcss"; @import "./views/dialogs/security/_AccessSecretStorageDialog.pcss"; @import "./views/dialogs/security/_CreateCrossSigningDialog.pcss"; diff --git a/res/css/compound/_Icon.pcss b/res/css/compound/_Icon.pcss index fe0924597f..39af843f27 100644 --- a/res/css/compound/_Icon.pcss +++ b/res/css/compound/_Icon.pcss @@ -25,20 +25,30 @@ limitations under the License. padding: 1px; } +.mx_Icon_accent { + color: $accent; +} + .mx_Icon_8 { - height: 8px; flex: 0 0 8px; + height: 8px; width: 8px; } .mx_Icon_16 { - height: 16px; flex: 0 0 16px; + height: 16px; width: 16px; } .mx_Icon_24 { - height: 24px; flex: 0 0 24px; + height: 24px; width: 24px; } + +.mx_Icon_32 { + flex: 0 0 32px; + height: 32px; + width: 32px; +} diff --git a/res/css/structures/_ErrorMessage.pcss b/res/css/structures/_ErrorMessage.pcss new file mode 100644 index 0000000000..ece0d7ea25 --- /dev/null +++ b/res/css/structures/_ErrorMessage.pcss @@ -0,0 +1,25 @@ +/* +Copyright 2022 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +.mx_ErrorMessage { + align-items: center; + color: $alert; + display: flex; + font-size: $font-12px; + gap: $spacing-8; + line-height: 1.2em; + min-height: 2.4em; +} diff --git a/res/css/structures/auth/_Login.pcss b/res/css/structures/auth/_Login.pcss index 2638daf876..329c2710cb 100644 --- a/res/css/structures/auth/_Login.pcss +++ b/res/css/structures/auth/_Login.pcss @@ -17,6 +17,8 @@ limitations under the License. .mx_Login_submit { @mixin mx_DialogButton; + font-size: 15px; + font-weight: 600; width: 100%; margin-top: 24px; margin-bottom: 24px; @@ -87,7 +89,7 @@ limitations under the License. div.mx_AccessibleButton_kind_link.mx_Login_forgot { display: block; - margin: 0 auto; + margin-top: 24px; &.mx_AccessibleButton_disabled { cursor: not-allowed; diff --git a/res/css/views/auth/_AuthBody.pcss b/res/css/views/auth/_AuthBody.pcss index bd139a2eac..f5e63b6661 100644 --- a/res/css/views/auth/_AuthBody.pcss +++ b/res/css/views/auth/_AuthBody.pcss @@ -17,12 +17,17 @@ limitations under the License. .mx_AuthBody { width: 500px; - font-size: $font-12px; - color: $authpage-secondary-color; + font-size: $font-14px; + color: $primary-content; background-color: $background; border-radius: 0 4px 4px 0; - padding: 25px 60px; + padding: 50px 32px; box-sizing: border-box; + min-height: 600px; + + b { + font-weight: 600; + } &.mx_AuthBody_flex { display: flex; @@ -32,7 +37,8 @@ limitations under the License. h1 { font-size: $font-24px; font-weight: $font-semi-bold; - margin-top: 8px; + margin-bottom: $spacing-20; + margin-top: $spacing-24; color: $authpage-primary-color; } @@ -52,6 +58,23 @@ limitations under the License. @mixin mx_Dialog_link; } + fieldset { + display: block; + } + + .mx_AuthBody_icon { + width: 40px; + } + + .mx_AuthBody_lockIcon { + height: 29px; + } + + .mx_AuthBody_text { + margin-bottom: $spacing-48; + margin-top: 0; + } + input[type="text"], input[type="password"] { color: $authpage-primary-color; @@ -76,6 +99,16 @@ limitations under the License. color: $alert; } + .mx_Login_submit { + height: 33px; + margin-top: $spacing-16; + } + + .mx_ErrorMessage { + margin-bottom: 12px; + margin-top: 2px; + } + .mx_Field input { box-sizing: border-box; } @@ -101,6 +134,43 @@ limitations under the License. } } +.mx_AuthBody_did-not-receive { + align-items: center; + color: $secondary-content; + display: flex; + gap: $spacing-8; + margin-bottom: 10px; + margin-top: $spacing-24; +} + +.mx_AuthBody_did-not-receive--centered { + justify-content: center; +} + +.mx_AuthBody_resend-button { + align-items: center; + border-radius: 8px; + color: $accent; + display: flex; + gap: $spacing-4; + padding: 4px; + + &:hover { + background-color: $system; + } +} + +.mx_AuthBody_emailPromptIcon { + width: 57px; +} + +.mx_AuthBody_emailPromptIcon--shifted { + margin-bottom: -17px; // Prevent layout jump by relative positioning. + position: relative; + top: -17px; // This icon is higher than the other icons. Shift up to prevent icon jumping. + width: 57px; +} + .mx_AuthBody_fieldRow { display: flex; margin-bottom: 10px; diff --git a/res/css/views/dialogs/_VerifyEMailDialog.pcss b/res/css/views/dialogs/_VerifyEMailDialog.pcss new file mode 100644 index 0000000000..78cc190022 --- /dev/null +++ b/res/css/views/dialogs/_VerifyEMailDialog.pcss @@ -0,0 +1,35 @@ +/* +Copyright 2022 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +.mx_VerifyEMailDialog { + .mx_Dialog { + color: $primary-content; + font-size: 14px; + padding: 16px; + text-align: center; + width: 485px; + + h1 { + font-size: $font-24px; + font-weight: 600; + } + + .mx_VerifyEMailDialog_text-light { + color: $secondary-content; + line-height: 20px; + } + } +} diff --git a/res/css/views/elements/_AccessibleButton.pcss b/res/css/views/elements/_AccessibleButton.pcss index 03a7465313..7dc95a5d8a 100644 --- a/res/css/views/elements/_AccessibleButton.pcss +++ b/res/css/views/elements/_AccessibleButton.pcss @@ -24,6 +24,7 @@ limitations under the License. &.mx_AccessibleButton_kind_primary_outline, &.mx_AccessibleButton_kind_primary_sm, &.mx_AccessibleButton_kind_link, + &.mx_AccessibleButton_kind_link_accent, &.mx_AccessibleButton_kind_link_inline, &.mx_AccessibleButton_kind_danger_inline, &.mx_AccessibleButton_kind_content_inline, diff --git a/res/img/element-icons/Checkbox.svg b/res/img/element-icons/Checkbox.svg new file mode 100644 index 0000000000..f1ee8b7dc2 --- /dev/null +++ b/res/img/element-icons/Checkbox.svg @@ -0,0 +1,3 @@ + + + diff --git a/res/img/element-icons/Email-icon.svg b/res/img/element-icons/Email-icon.svg new file mode 100644 index 0000000000..c92b153cf0 --- /dev/null +++ b/res/img/element-icons/Email-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/res/img/element-icons/lock.svg b/res/img/element-icons/lock.svg index 06fe52a391..5ad69d9f1a 100644 --- a/res/img/element-icons/lock.svg +++ b/res/img/element-icons/lock.svg @@ -1,3 +1 @@ - - - + \ No newline at end of file diff --git a/res/img/element-icons/retry.svg b/res/img/element-icons/retry.svg index 54e9f9c580..6e5b8651fc 100644 --- a/res/img/element-icons/retry.svg +++ b/res/img/element-icons/retry.svg @@ -1,3 +1,7 @@ - - + + diff --git a/src/PasswordReset.ts b/src/PasswordReset.ts index df812bafb2..8f3c9bd91e 100644 --- a/src/PasswordReset.ts +++ b/src/PasswordReset.ts @@ -19,6 +19,8 @@ import { createClient, IRequestTokenResponse, MatrixClient } from 'matrix-js-sdk import { _t } from './languageHandler'; +const CHECK_EMAIL_VERIFIED_POLL_INTERVAL = 2000; + /** * Allows a user to reset their password on a homeserver. * @@ -29,9 +31,10 @@ import { _t } from './languageHandler'; export default class PasswordReset { private client: MatrixClient; private clientSecret: string; - private password: string; - private sessionId: string; - private logoutDevices: boolean; + private password = ""; + private sessionId = ""; + private logoutDevices = false; + private sendAttempt = 0; /** * Configure the endpoints for password resetting. @@ -54,14 +57,40 @@ export default class PasswordReset { * @param {boolean} logoutDevices Should all devices be signed out after the reset? Defaults to `true`. * @return {Promise} Resolves when the email has been sent. Then call checkEmailLinkClicked(). */ - public resetPassword( + public async resetPassword( emailAddress: string, newPassword: string, logoutDevices = true, ): Promise { this.password = newPassword; this.logoutDevices = logoutDevices; - return this.client.requestPasswordEmailToken(emailAddress, this.clientSecret, 1).then((res) => { + this.sendAttempt++; + + try { + const result = await this.client.requestPasswordEmailToken( + emailAddress, + this.clientSecret, + this.sendAttempt, + ); + this.sessionId = result.sid; + return result; + } catch (err: any) { + if (err.errcode === 'M_THREEPID_NOT_FOUND') { + err.message = _t('This email address was not found'); + } else if (err.httpStatus) { + err.message = err.message + ` (Status ${err.httpStatus})`; + } + throw err; + } + } + + /** + * Request a password reset token. + * This will trigger a side-effect of sending an email to the provided email address. + */ + public requestResetToken(emailAddress: string): Promise { + this.sendAttempt++; + return this.client.requestPasswordEmailToken(emailAddress, this.clientSecret, this.sendAttempt).then((res) => { this.sessionId = res.sid; return res; }, function(err) { @@ -74,6 +103,29 @@ export default class PasswordReset { }); } + public async setNewPassword(password: string): Promise { + this.password = password; + await this.checkEmailLinkClicked(); + } + + public async retrySetNewPassword(password: string): Promise { + this.password = password; + return new Promise((resolve) => { + this.tryCheckEmailLinkClicked(resolve); + }); + } + + private tryCheckEmailLinkClicked(resolve: Function): void { + this.checkEmailLinkClicked() + .then(() => resolve()) + .catch(() => { + setTimeout( + () => this.tryCheckEmailLinkClicked(resolve), + CHECK_EMAIL_VERIFIED_POLL_INTERVAL, + ); + }); + } + /** * Checks if the email link has been clicked by attempting to change the password * for the mxid linked to the email. @@ -98,7 +150,7 @@ export default class PasswordReset { threepid_creds: creds, threepidCreds: creds, }, this.password, this.logoutDevices); - } catch (err) { + } catch (err: any) { if (err.httpStatus === 401) { err.message = _t('Failed to verify email address: make sure you clicked the link in the email'); } else if (err.httpStatus === 404) { diff --git a/src/components/structures/ErrorMessage.tsx b/src/components/structures/ErrorMessage.tsx new file mode 100644 index 0000000000..9532eab30f --- /dev/null +++ b/src/components/structures/ErrorMessage.tsx @@ -0,0 +1,40 @@ +/* +Copyright 2022 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import React, { ReactNode } from 'react'; + +import { Icon as WarningBadgeIcon } from "../../../res/img/element-icons/warning-badge.svg"; + +interface ErrorMessageProps { + message: string | ReactNode | null; +} + +/** + * Error message component. + * Reserves two lines to display errors to prevent layout shifts when the error pops up. + */ +export const ErrorMessage: React.FC = ({ + message, +}) => { + const icon = message + ? + : null; + + return
+ { icon } + { message } +
; +}; diff --git a/src/components/structures/MatrixChat.tsx b/src/components/structures/MatrixChat.tsx index c64bc2b843..59c9ec32b8 100644 --- a/src/components/structures/MatrixChat.tsx +++ b/src/components/structures/MatrixChat.tsx @@ -2086,7 +2086,6 @@ export default class MatrixChat extends React.PureComponent { ); diff --git a/src/components/structures/auth/ForgotPassword.tsx b/src/components/structures/auth/ForgotPassword.tsx index 4605f8fa0e..8171825fab 100644 --- a/src/components/structures/auth/ForgotPassword.tsx +++ b/src/components/structures/auth/ForgotPassword.tsx @@ -16,104 +16,102 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React from 'react'; -import classNames from 'classnames'; -import { logger } from "matrix-js-sdk/src/logger"; +import React, { ReactNode } from 'react'; +import { logger } from 'matrix-js-sdk/src/logger'; import { createClient } from "matrix-js-sdk/src/matrix"; import { _t, _td } from '../../../languageHandler'; import Modal from "../../../Modal"; import PasswordReset from "../../../PasswordReset"; -import AutoDiscoveryUtils from "../../../utils/AutoDiscoveryUtils"; import AuthPage from "../../views/auth/AuthPage"; -import ServerPicker from "../../views/elements/ServerPicker"; -import EmailField from "../../views/auth/EmailField"; import PassphraseField from '../../views/auth/PassphraseField'; import { PASSWORD_MIN_SCORE } from '../../views/auth/RegistrationForm'; -import InlineSpinner from '../../views/elements/InlineSpinner'; -import Spinner from "../../views/elements/Spinner"; -import QuestionDialog from "../../views/dialogs/QuestionDialog"; -import ErrorDialog from "../../views/dialogs/ErrorDialog"; import AuthHeader from "../../views/auth/AuthHeader"; import AuthBody from "../../views/auth/AuthBody"; import PassphraseConfirmField from "../../views/auth/PassphraseConfirmField"; -import AccessibleButton from '../../views/elements/AccessibleButton'; import StyledCheckbox from '../../views/elements/StyledCheckbox'; import { ValidatedServerConfig } from '../../../utils/ValidatedServerConfig'; +import { Icon as LockIcon } from "../../../../res/img/element-icons/lock.svg"; +import QuestionDialog from '../../views/dialogs/QuestionDialog'; +import { EnterEmail } from './forgot-password/EnterEmail'; +import { CheckEmail } from './forgot-password/CheckEmail'; +import Field from '../../views/elements/Field'; +import { ErrorMessage } from '../ErrorMessage'; +import { Icon as CheckboxIcon } from "../../../../res/img/element-icons/Checkbox.svg"; +import { VerifyEmailModal } from './forgot-password/VerifyEmailModal'; +import Spinner from '../../views/elements/Spinner'; +import { formatSeconds } from '../../../DateUtils'; +import AutoDiscoveryUtils from '../../../utils/AutoDiscoveryUtils'; enum Phase { - // Show the forgot password inputs - Forgot = 1, + // Show email input + EnterEmail = 1, // Email is in the process of being sent SendingEmail = 2, // Email has been sent EmailSent = 3, - // User has clicked the link in email and completed reset - Done = 4, + // Show new password input + PasswordInput = 4, + // Password is in the process of being reset + ResettingPassword = 5, + // All done + Done = 6, } -interface IProps { +interface Props { serverConfig: ValidatedServerConfig; - onServerConfigChange: (serverConfig: ValidatedServerConfig) => void; onLoginClick?: () => void; onComplete: () => void; } -interface IState { +interface State { phase: Phase; email: string; password: string; password2: string; - errorText: string; + errorText: string | ReactNode | null; // We perform liveliness checks later, but for now suppress the errors. // We also track the server dead errors independently of the regular errors so // that we can render it differently, and override any other error the user may // be seeing. serverIsAlive: boolean; - serverErrorIsFatal: boolean; serverDeadError: string; - currentHttpRequest?: Promise; - serverSupportsControlOfDevicesLogout: boolean; logoutDevices: boolean; } -enum ForgotPasswordField { - Email = 'field_email', - Password = 'field_password', - PasswordConfirm = 'field_password_confirm', -} - -export default class ForgotPassword extends React.Component { +export default class ForgotPassword extends React.Component { private reset: PasswordReset; + private fieldPassword: Field | null = null; + private fieldPasswordConfirm: Field | null = null; - state: IState = { - phase: Phase.Forgot, - email: "", - password: "", - password2: "", - errorText: null, - - // We perform liveliness checks later, but for now suppress the errors. - // We also track the server dead errors independently of the regular errors so - // that we can render it differently, and override any other error the user may - // be seeing. - serverIsAlive: true, - serverErrorIsFatal: false, - serverDeadError: "", - serverSupportsControlOfDevicesLogout: false, - logoutDevices: false, - }; + public constructor(props: Props) { + super(props); + this.state = { + phase: Phase.EnterEmail, + email: "", + password: "", + password2: "", + errorText: null, + // We perform liveliness checks later, but for now suppress the errors. + // We also track the server dead errors independently of the regular errors so + // that we can render it differently, and override any other error the user may + // be seeing. + serverIsAlive: true, + serverDeadError: "", + serverSupportsControlOfDevicesLogout: false, + logoutDevices: false, + }; + this.reset = new PasswordReset(this.props.serverConfig.hsUrl, this.props.serverConfig.isUrl); + } public componentDidMount() { - this.reset = null; - this.checkServerLiveliness(this.props.serverConfig); this.checkServerCapabilities(this.props.serverConfig); } - public componentDidUpdate(prevProps: Readonly) { + public componentDidUpdate(prevProps: Readonly) { if (prevProps.serverConfig.hsUrl !== this.props.serverConfig.hsUrl || prevProps.serverConfig.isUrl !== this.props.serverConfig.isUrl ) { @@ -125,7 +123,7 @@ export default class ForgotPassword extends React.Component { } } - private async checkServerLiveliness(serverConfig): Promise { + private async checkServerLiveliness(serverConfig: ValidatedServerConfig): Promise { try { await AutoDiscoveryUtils.validateServerConfigWithStaticUrls( serverConfig.hsUrl, @@ -135,8 +133,15 @@ export default class ForgotPassword extends React.Component { this.setState({ serverIsAlive: true, }); - } catch (e) { - this.setState(AutoDiscoveryUtils.authComponentStateForError(e, "forgot_password") as IState); + } catch (e: any) { + const { + serverIsAlive, + serverDeadError, + } = AutoDiscoveryUtils.authComponentStateForError(e, "forgot_password"); + this.setState({ + serverIsAlive, + errorText: serverDeadError, + }); } } @@ -153,94 +158,85 @@ export default class ForgotPassword extends React.Component { }); } - public submitPasswordReset(email: string, password: string, logoutDevices = true): void { + private async onPhaseEmailInputSubmit() { + this.phase = Phase.SendingEmail; + + if (await this.sendVerificationMail()) { + this.phase = Phase.EmailSent; + return; + } + + this.phase = Phase.EnterEmail; + } + + private sendVerificationMail = async (): Promise => { + try { + await this.reset.requestResetToken(this.state.email); + return true; + } catch (err: any) { + this.handleError(err); + } + + return false; + }; + + private handleError(err: any): void { + if (err?.httpStatus === 429) { + // 429: rate limit + const retryAfterMs = parseInt(err?.data?.retry_after_ms, 10); + + const errorText = isNaN(retryAfterMs) + ? _t("Too many attempts in a short time. Wait some time before trying again.") + : _t( + "Too many attempts in a short time. Retry after %(timeout)s.", + { + timeout: formatSeconds(retryAfterMs / 1000), + }, + ); + + this.setState({ + errorText, + }); + return; + } + + if (err?.name === "ConnectionError") { + this.setState({ + errorText: _t("Cannot reach homeserver") + ": " + + _t("Ensure you have a stable internet connection, or get in touch with the server admin"), + }); + return; + } + this.setState({ - phase: Phase.SendingEmail, - }); - this.reset = new PasswordReset(this.props.serverConfig.hsUrl, this.props.serverConfig.isUrl); - this.reset.resetPassword(email, password, logoutDevices).then(() => { - this.setState({ - phase: Phase.EmailSent, - }); - }, (err) => { - this.showErrorDialog(_t('Failed to send email') + ": " + err.message); - this.setState({ - phase: Phase.Forgot, - }); + errorText: err.message, }); } - private onVerify = async (ev: React.MouseEvent): Promise => { - ev.preventDefault(); - if (!this.reset) { - logger.error("onVerify called before submitPasswordReset!"); - return; - } - if (this.state.currentHttpRequest) return; + private async onPhaseEmailSentSubmit() { + this.setState({ + phase: Phase.PasswordInput, + }); + } - try { - await this.handleHttpRequest(this.reset.checkEmailLinkClicked()); - this.setState({ phase: Phase.Done }); - } catch (err) { - this.showErrorDialog(err.message); - } - }; + private set phase(phase: Phase) { + this.setState({ phase }); + } - private onSubmitForm = async (ev: React.FormEvent): Promise => { - ev.preventDefault(); - if (this.state.currentHttpRequest) return; - - // refresh the server errors, just in case the server came back online - await this.handleHttpRequest(this.checkServerLiveliness(this.props.serverConfig)); - - const allFieldsValid = await this.verifyFieldsBeforeSubmit(); - if (!allFieldsValid) { - return; - } - - if (this.state.logoutDevices) { - const { finished } = Modal.createDialog<[boolean]>(QuestionDialog, { - title: _t('Warning!'), - description: -
-

{ !this.state.serverSupportsControlOfDevicesLogout ? - _t( - "Resetting your password on this homeserver will cause all of your devices to be " + - "signed out. This will delete the message encryption keys stored on them, " + - "making encrypted chat history unreadable.", - ) : - _t( - "Signing out your devices will delete the message encryption keys stored on them, " + - "making encrypted chat history unreadable.", - ) - }

-

{ _t( - "If you want to retain access to your chat history in encrypted rooms, set up Key Backup " + - "or export your message keys from one of your other devices before proceeding.", - ) }

-
, - button: _t('Continue'), - }); - const [confirmed] = await finished; - - if (!confirmed) return; - } - - this.submitPasswordReset(this.state.email, this.state.password, this.state.logoutDevices); - }; - - private async verifyFieldsBeforeSubmit() { + private async verifyFieldsBeforeSubmit(): Promise { const fieldIdsInDisplayOrder = [ - ForgotPasswordField.Email, - ForgotPasswordField.Password, - ForgotPasswordField.PasswordConfirm, + this.fieldPassword, + this.fieldPasswordConfirm, ]; - const invalidFields = []; - for (const fieldId of fieldIdsInDisplayOrder) { - const valid = await this[fieldId].validate({ allowEmpty: false }); + const invalidFields: Field[] = []; + + for (const field of fieldIdsInDisplayOrder) { + if (!field) continue; + + const valid = await field.validate({ allowEmpty: false }); if (!valid) { - invalidFields.push(this[fieldId]); + invalidFields.push(field); } } @@ -256,6 +252,78 @@ export default class ForgotPassword extends React.Component { return false; } + private async onPhasePasswordInputSubmit(): Promise { + if (!await this.verifyFieldsBeforeSubmit()) return; + + if (this.state.logoutDevices) { + const logoutDevicesConfirmation = await this.renderConfirmLogoutDevicesDialog(); + if (!logoutDevicesConfirmation) return; + } + + this.phase = Phase.ResettingPassword; + + try { + await this.reset.setNewPassword(this.state.password); + } catch (err: any) { + if (err.httpStatus !== 401) { + // 401 = waiting for email verification, else unknown error + this.handleError(err); + return; + } + } + + const modal = Modal.createDialog( + VerifyEmailModal, + { + email: this.state.email, + errorText: this.state.errorText, + onResendClick: this.sendVerificationMail, + }, + "mx_VerifyEMailDialog", + false, + false, + { + // this modal cannot be dismissed except reset is done or forced + onBeforeClose: async (reason?: string) => { + return this.state.phase === Phase.Done || reason === "force"; + }, + }, + ); + + await this.reset.retrySetNewPassword(this.state.password); + this.phase = Phase.Done; + modal.close(); + } + + private onSubmitForm = async (ev: React.FormEvent): Promise => { + ev.preventDefault(); + + // Should not happen because of disabled forms, but just return if currently doing an action. + if ([Phase.SendingEmail, Phase.ResettingPassword].includes(this.state.phase)) return; + + this.setState({ + errorText: "", + }); + + // Refresh the server errors. Just in case the server came back online of went offline. + await this.checkServerLiveliness(this.props.serverConfig); + + // Server error + if (!this.state.serverIsAlive) return; + + switch (this.state.phase) { + case Phase.EnterEmail: + this.onPhaseEmailInputSubmit(); + break; + case Phase.EmailSent: + this.onPhaseEmailSentSubmit(); + break; + case Phase.PasswordInput: + this.onPhasePasswordInputSubmit(); + break; + } + }; + private onInputChanged = (stateKey: string, ev: React.FormEvent) => { let value = ev.currentTarget.value; if (stateKey === "email") value = value.trim(); @@ -264,139 +332,109 @@ export default class ForgotPassword extends React.Component { } as any); }; - private onLoginClick = (ev: React.MouseEvent): void => { - ev.preventDefault(); - ev.stopPropagation(); - this.props.onLoginClick(); - }; - - public showErrorDialog(description: string, title?: string) { - Modal.createDialog(ErrorDialog, { - title, - description, - }); + renderEnterEmail(): JSX.Element { + return ; } - private handleHttpRequest(request: Promise): Promise { - this.setState({ - currentHttpRequest: request, - }); - return request.finally(() => { - this.setState({ - currentHttpRequest: undefined, - }); + async renderConfirmLogoutDevicesDialog(): Promise { + const { finished } = Modal.createDialog<[boolean]>(QuestionDialog, { + title: _t('Warning!'), + description: +
+

{ !this.state.serverSupportsControlOfDevicesLogout ? + _t( + "Resetting your password on this homeserver will cause all of your devices to be " + + "signed out. This will delete the message encryption keys stored on them, " + + "making encrypted chat history unreadable.", + ) : + _t( + "Signing out your devices will delete the message encryption keys stored on them, " + + "making encrypted chat history unreadable.", + ) + }

+

{ _t( + "If you want to retain access to your chat history in encrypted rooms, set up Key Backup " + + "or export your message keys from one of your other devices before proceeding.", + ) }

+
, + button: _t('Continue'), }); + const [confirmed] = await finished; + return confirmed; } - renderForgot() { - let errorText = null; - const err = this.state.errorText; - if (err) { - errorText =
{ err }
; - } + renderCheckEmail(): JSX.Element { + return ; + } - let serverDeadSection; - if (!this.state.serverIsAlive) { - const classes = classNames({ - "mx_Login_error": true, - "mx_Login_serverError": true, - "mx_Login_serverErrorNonFatal": !this.state.serverErrorIsFatal, - }); - serverDeadSection = ( -
- { this.state.serverDeadError } -
- ); - } + renderSetPassword(): JSX.Element { + const submitButtonChild = this.state.phase === Phase.ResettingPassword + ? + : _t("Reset password"); - return
- { errorText } - { serverDeadSection } - + return <> + +

{ _t("Reset your password") }

-
- this[ForgotPasswordField.Email] = field} - autoFocus={true} - onChange={this.onInputChanged.bind(this, "email")} - /> -
-
- this[ForgotPasswordField.Password] = field} - onChange={this.onInputChanged.bind(this, "password")} - autoComplete="new-password" - /> - this[ForgotPasswordField.PasswordConfirm] = field} - onChange={this.onInputChanged.bind(this, "password2")} - autoComplete="new-password" - /> -
- { this.state.serverSupportsControlOfDevicesLogout ? +
- this.setState({ logoutDevices: !this.state.logoutDevices })} checked={this.state.logoutDevices}> - { _t("Sign out all devices") } - -
: null - } - { _t( - 'A verification email will be sent to your inbox to confirm ' + - 'setting your new password.', - ) } - + this.fieldPassword = field} + onChange={this.onInputChanged.bind(this, "password")} + autoComplete="new-password" + /> + this.fieldPasswordConfirm = field} + onChange={this.onInputChanged.bind(this, "password2")} + autoComplete="new-password" + /> +
+ { this.state.serverSupportsControlOfDevicesLogout ? +
+ this.setState({ logoutDevices: !this.state.logoutDevices })} checked={this.state.logoutDevices}> + { _t("Sign out of all devices") } + +
: null + } + { this.state.errorText && } + + - - { _t('Sign in instead') } - - ; - } - - renderSendingEmail() { - return ; - } - - renderEmailSent() { - return
- { _t("An email has been sent to %(emailAddress)s. Once you've followed the " + - "link it contains, click below.", { emailAddress: this.state.email }) } -
- - { this.state.currentHttpRequest && ( -
) - } -
; + ; } renderDone() { - return
-

{ _t("Your password has been reset.") }

+ return <> + +

{ _t("Your password has been reset.") }

{ this.state.logoutDevices ?

{ _t( "You have been logged out of all devices and will no longer receive " + @@ -410,33 +448,40 @@ export default class ForgotPassword extends React.Component { type="button" onClick={this.props.onComplete} value={_t('Return to login screen')} /> -

; + ; } render() { - let resetPasswordJsx; + let resetPasswordJsx: JSX.Element; + switch (this.state.phase) { - case Phase.Forgot: - resetPasswordJsx = this.renderForgot(); - break; + case Phase.EnterEmail: case Phase.SendingEmail: - resetPasswordJsx = this.renderSendingEmail(); + resetPasswordJsx = this.renderEnterEmail(); break; case Phase.EmailSent: - resetPasswordJsx = this.renderEmailSent(); + resetPasswordJsx = this.renderCheckEmail(); + break; + case Phase.PasswordInput: + case Phase.ResettingPassword: + resetPasswordJsx = this.renderSetPassword(); break; case Phase.Done: resetPasswordJsx = this.renderDone(); break; default: - resetPasswordJsx =
; + // This should not happen. However, it is logged and the user is sent to the start. + logger.warn(`unknown forgot password phase ${this.state.phase}`); + this.setState({ + phase: Phase.EnterEmail, + }); + return; } return ( -

{ _t('Set a new password') }

{ resetPasswordJsx }
diff --git a/src/components/structures/auth/forgot-password/CheckEmail.tsx b/src/components/structures/auth/forgot-password/CheckEmail.tsx new file mode 100644 index 0000000000..27fa82f25e --- /dev/null +++ b/src/components/structures/auth/forgot-password/CheckEmail.tsx @@ -0,0 +1,84 @@ +/* +Copyright 2022 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import React, { ReactNode } from "react"; + +import AccessibleButton from "../../../views/elements/AccessibleButton"; +import { Icon as EMailPromptIcon } from "../../../../../res/img/element-icons/email-prompt.svg"; +import { Icon as RetryIcon } from "../../../../../res/img/element-icons/retry.svg"; +import { _t } from '../../../../languageHandler'; +import Tooltip, { Alignment } from "../../../views/elements/Tooltip"; +import { useTimeoutToggle } from "../../../../hooks/useTimeoutToggle"; +import { ErrorMessage } from "../../ErrorMessage"; + +interface CheckEmailProps { + email: string; + errorText: string | ReactNode | null; + onResendClick: () => Promise; + onSubmitForm: (ev: React.FormEvent) => void; +} + +/** + * This component renders the email verification view of the forgot password flow. + */ +export const CheckEmail: React.FC = ({ + email, + errorText, + onSubmitForm, + onResendClick, +}) => { + const { toggle: toggleTooltipVisible, value: tooltipVisible } = useTimeoutToggle(false, 2500); + + const onResendClickFn = async (): Promise => { + await onResendClick(); + toggleTooltipVisible(); + }; + + return <> + +

{ _t("Check your email to continue") }

+

+ { _t( + "Follow the instructions sent to %(email)s", + { email: email }, + { b: t => { t } }, + ) } +

+
+ { _t("Did not receive it?") } + + + { _t("Resend") } + + +
+ { errorText && } + + ; +}; diff --git a/src/components/structures/auth/forgot-password/EnterEmail.tsx b/src/components/structures/auth/forgot-password/EnterEmail.tsx new file mode 100644 index 0000000000..a630291ae2 --- /dev/null +++ b/src/components/structures/auth/forgot-password/EnterEmail.tsx @@ -0,0 +1,98 @@ +/* +Copyright 2022 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import React, { ReactNode, useRef } from "react"; + +import { Icon as EmailIcon } from "../../../../../res/img/element-icons/Email-icon.svg"; +import { _t, _td } from '../../../../languageHandler'; +import EmailField from "../../../views/auth/EmailField"; +import { ErrorMessage } from "../../ErrorMessage"; +import Spinner from "../../../views/elements/Spinner"; +import Field from "../../../views/elements/Field"; + +interface EnterEmailProps { + email: string; + errorText: string | ReactNode | null; + homeserver: string; + loading: boolean; + onInputChanged: (stateKey: string, ev: React.FormEvent) => void; + onSubmitForm: (ev: React.FormEvent) => void; +} + +/** + * This component renders the email input view of the forgot password flow. + */ +export const EnterEmail: React.FC = ({ + email, + errorText, + homeserver, + loading, + onInputChanged, + onSubmitForm, +}) => { + const submitButtonChild = loading + ? + : _t("Send email"); + + const emailFieldRef = useRef(null); + + const onSubmit = async (event: React.FormEvent) => { + if (await emailFieldRef.current?.validate({ allowEmpty: false })) { + onSubmitForm(event); + return; + } + + emailFieldRef.current?.focus(); + emailFieldRef.current?.validate({ allowEmpty: false, focused: true }); + }; + + return <> + +

{ _t("Enter your email to reset password") }

+

+ { + _t( + "%(homeserver)s will send you a verification link to let you reset your password.", + { homeserver }, + { b: t => { t } }, + ) + } +

+
+
+
+ ) => onInputChanged("email", event)} + fieldRef={emailFieldRef} + /> +
+ { errorText && } + +
+
+ ; +}; diff --git a/src/components/structures/auth/forgot-password/VerifyEmailModal.tsx b/src/components/structures/auth/forgot-password/VerifyEmailModal.tsx new file mode 100644 index 0000000000..d63e4c97d7 --- /dev/null +++ b/src/components/structures/auth/forgot-password/VerifyEmailModal.tsx @@ -0,0 +1,78 @@ +/* +Copyright 2022 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import React from "react"; + +import { _t } from "../../../../languageHandler"; +import AccessibleButton from "../../../views/elements/AccessibleButton"; +import { Icon as RetryIcon } from "../../../../../res/img/element-icons/retry.svg"; +import { Icon as EmailPromptIcon } from "../../../../../res/img/element-icons/email-prompt.svg"; +import Tooltip, { Alignment } from "../../../views/elements/Tooltip"; +import { useTimeoutToggle } from "../../../../hooks/useTimeoutToggle"; +import { ErrorMessage } from "../../ErrorMessage"; + +interface Props { + email: string; + errorText: string | null; + onResendClick: () => Promise; +} + +export const VerifyEmailModal: React.FC = ({ + email, + errorText, + onResendClick, +}) => { + const { toggle: toggleTooltipVisible, value: tooltipVisible } = useTimeoutToggle(false, 2500); + + const onResendClickFn = async (): Promise => { + await onResendClick(); + toggleTooltipVisible(); + }; + + return <> + +

{ _t("Verify your email to continue") }

+

+ { _t( + `We need to know it’s you before resetting your password. + Click the link in the email we just sent to %(email)s`, + { + email, + }, + { + b: sub => { sub }, + }, + ) } +

+
+ { _t("Did not receive it?") } + + + { _t("Resend") } + + + { errorText && } +
+ ; +}; diff --git a/src/components/views/elements/Field.tsx b/src/components/views/elements/Field.tsx index 59f16caacd..3a0c3ef155 100644 --- a/src/components/views/elements/Field.tsx +++ b/src/components/views/elements/Field.tsx @@ -290,7 +290,7 @@ export default class Field extends React.PureComponent { let fieldTooltip; if (tooltipContent || this.state.feedback) { fieldTooltip = { + const timeoutId = useRef(); + const [value, setValue] = useState(defaultValue); + + const toggle = () => { + setValue(!defaultValue); + timeoutId.current = setTimeout(() => setValue(defaultValue), timeoutMs); + }; + + useEffect(() => { + return () => { + clearTimeout(timeoutId.current); + }; + }); + + return { + toggle, + value, + }; +}; diff --git a/src/i18n/strings/en_EN.json b/src/i18n/strings/en_EN.json index 5146ef4922..549a1b3e98 100644 --- a/src/i18n/strings/en_EN.json +++ b/src/i18n/strings/en_EN.json @@ -3424,24 +3424,20 @@ "Device verified": "Device verified", "Really reset verification keys?": "Really reset verification keys?", "Skip verification for now": "Skip verification for now", - "Failed to send email": "Failed to send email", + "Too many attempts in a short time. Wait some time before trying again.": "Too many attempts in a short time. Wait some time before trying again.", + "Too many attempts in a short time. Retry after %(timeout)s.": "Too many attempts in a short time. Retry after %(timeout)s.", "Resetting your password on this homeserver will cause all of your devices to be signed out. This will delete the message encryption keys stored on them, making encrypted chat history unreadable.": "Resetting your password on this homeserver will cause all of your devices to be signed out. This will delete the message encryption keys stored on them, making encrypted chat history unreadable.", "Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.": "Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.", "If you want to retain access to your chat history in encrypted rooms, set up Key Backup or export your message keys from one of your other devices before proceeding.": "If you want to retain access to your chat history in encrypted rooms, set up Key Backup or export your message keys from one of your other devices before proceeding.", - "The email address linked to your account must be entered.": "The email address linked to your account must be entered.", - "The email address doesn't appear to be valid.": "The email address doesn't appear to be valid.", + "Reset password": "Reset password", + "Reset your password": "Reset your password", + "Confirm new password": "Confirm new password", "A new password must be entered.": "A new password must be entered.", "New passwords must match each other.": "New passwords must match each other.", - "Sign out all devices": "Sign out all devices", - "A verification email will be sent to your inbox to confirm setting your new password.": "A verification email will be sent to your inbox to confirm setting your new password.", - "Send Reset Email": "Send Reset Email", - "Sign in instead": "Sign in instead", - "An email has been sent to %(emailAddress)s. Once you've followed the link it contains, click below.": "An email has been sent to %(emailAddress)s. Once you've followed the link it contains, click below.", - "I have verified my email address": "I have verified my email address", + "Sign out of all devices": "Sign out of all devices", "Your password has been reset.": "Your password has been reset.", "You have been logged out of all devices and will no longer receive push notifications. To re-enable notifications, sign in again on each device.": "You have been logged out of all devices and will no longer receive push notifications. To re-enable notifications, sign in again on each device.", "Return to login screen": "Return to login screen", - "Set a new password": "Set a new password", "Invalid homeserver discovery response": "Invalid homeserver discovery response", "Failed to get autodiscovery configuration from server": "Failed to get autodiscovery configuration from server", "Invalid base_url for m.homeserver": "Invalid base_url for m.homeserver", @@ -3501,6 +3497,16 @@ "You're signed out": "You're signed out", "Clear personal data": "Clear personal data", "Warning: Your personal data (including encryption keys) is still stored in this session. Clear it if you're finished using this session, or want to sign in to another account.": "Warning: Your personal data (including encryption keys) is still stored in this session. Clear it if you're finished using this session, or want to sign in to another account.", + "Follow the instructions sent to %(email)s": "Follow the instructions sent to %(email)s", + "Did not receive it?": "Did not receive it?", + "Verification link email resent!": "Verification link email resent!", + "Send email": "Send email", + "Enter your email to reset password": "Enter your email to reset password", + "%(homeserver)s will send you a verification link to let you reset your password.": "%(homeserver)s will send you a verification link to let you reset your password.", + "The email address linked to your account must be entered.": "The email address linked to your account must be entered.", + "The email address doesn't appear to be valid.": "The email address doesn't appear to be valid.", + "Verify your email to continue": "Verify your email to continue", + "We need to know it’s you before resetting your password.\n Click the link in the email we just sent to %(email)s": "We need to know it’s you before resetting your password.\n Click the link in the email we just sent to %(email)s", "Commands": "Commands", "Command Autocomplete": "Command Autocomplete", "Emoji Autocomplete": "Emoji Autocomplete", diff --git a/test/components/structures/auth/ForgotPassword-test.tsx b/test/components/structures/auth/ForgotPassword-test.tsx index 88cc36e8dd..cb379153c4 100644 --- a/test/components/structures/auth/ForgotPassword-test.tsx +++ b/test/components/structures/auth/ForgotPassword-test.tsx @@ -14,89 +14,287 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React from 'react'; -import { fireEvent, render, screen, waitFor, waitForElementToBeRemoved } from "@testing-library/react"; -import { createClient, MatrixClient } from 'matrix-js-sdk/src/matrix'; -import { mocked } from 'jest-mock'; -import fetchMock from "fetch-mock-jest"; +import React from "react"; +import { mocked } from "jest-mock"; +import { act, render, RenderResult, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MatrixClient, createClient } from "matrix-js-sdk/src/matrix"; -import SdkConfig, { DEFAULTS } from '../../../../src/SdkConfig'; -import { mkServerConfig, mockPlatformPeg, unmockPlatformPeg } from "../../../test-utils"; import ForgotPassword from "../../../../src/components/structures/auth/ForgotPassword"; -import PasswordReset from "../../../../src/PasswordReset"; +import { ValidatedServerConfig } from "../../../../src/utils/ValidatedServerConfig"; +import { flushPromisesWithFakeTimers, stubClient } from "../../../test-utils"; +import Modal from "../../../../src/Modal"; +import AutoDiscoveryUtils from "../../../../src/utils/AutoDiscoveryUtils"; -jest.mock('matrix-js-sdk/src/matrix'); -jest.mock("../../../../src/PasswordReset", () => (jest.fn().mockReturnValue({ - resetPassword: jest.fn().mockReturnValue(new Promise(() => {})), -}))); -jest.useFakeTimers(); +jest.mock("matrix-js-sdk/src/matrix", () => ({ + ...jest.requireActual("matrix-js-sdk/src/matrix"), + createClient: jest.fn(), +})); -describe('', () => { - const mockClient = mocked({ - doesServerSupportLogoutDevices: jest.fn().mockResolvedValue(true), - } as unknown as MatrixClient); +describe("", () => { + const testEmail = "user@example.com"; + const testSid = "sid42"; + const testPassword = "cRaZyP4ssw0rd!"; + let client: MatrixClient; + let serverConfig: ValidatedServerConfig; + let onComplete: () => void; + let renderResult: RenderResult; - beforeEach(function() { - SdkConfig.put({ - ...DEFAULTS, - disable_custom_urls: true, + const typeIntoField = async (label: string, value: string): Promise => { + await act(async () => { + await userEvent.type(screen.getByLabelText(label), value, { delay: null }); + // the message is shown after some time + jest.advanceTimersByTime(500); }); - mocked(createClient).mockImplementation(opts => { - mockClient.idBaseUrl = opts.idBaseUrl; - mockClient.baseUrl = opts.baseUrl; - return mockClient; - }); - fetchMock.get("https://matrix.org/_matrix/client/versions", { - unstable_features: {}, - versions: [], - }); - mockPlatformPeg({ - startSingleSignOn: jest.fn(), - }); - }); - - afterEach(function() { - fetchMock.restore(); - SdkConfig.unset(); // we touch the config, so clean up - unmockPlatformPeg(); - }); - - const defaultProps = { - defaultDeviceDisplayName: 'test-device-display-name', - onServerConfigChange: jest.fn(), - onLoginClick: jest.fn(), - onComplete: jest.fn(), }; - function getRawComponent(hsUrl = "https://matrix.org", isUrl = "https://vector.im") { - return ; - } - - it("should handle serverConfig updates correctly", async () => { - const { container, rerender } = render(getRawComponent()); - await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading...")); - - fetchMock.get("https://server2/_matrix/client/versions", { - unstable_features: {}, - versions: [], + const submitForm = async (submitLabel: string): Promise => { + await act(async () => { + await userEvent.click(screen.getByText(submitLabel), { delay: null }); }); - fetchMock.get("https://vector.im/_matrix/identity/api/v1", {}); - rerender(getRawComponent("https://server2")); + }; - const email = "email@addy.com"; - const pass = "thisIsAT0tallySecurePassword"; + beforeEach(() => { + client = stubClient(); + mocked(createClient).mockReturnValue(client); - fireEvent.change(container.querySelector('[label=Email]'), { target: { value: email } }); - fireEvent.change(container.querySelector('[label="New Password"]'), { target: { value: pass } }); - fireEvent.change(container.querySelector('[label=Confirm]'), { target: { value: pass } }); - fireEvent.change(container.querySelector('[type=checkbox]')); // this allows us to bypass the modal - fireEvent.submit(container.querySelector("form")); + serverConfig = new ValidatedServerConfig(); + serverConfig.hsName = "example.com"; - await waitFor(() => { - return expect(PasswordReset).toHaveBeenCalledWith("https://server2", expect.anything()); - }, { timeout: 5000 }); + onComplete = jest.fn(); + + jest.spyOn(AutoDiscoveryUtils, "validateServerConfigWithStaticUrls").mockResolvedValue(serverConfig); + jest.spyOn(AutoDiscoveryUtils, "authComponentStateForError"); + }); + + afterEach(() => { + // clean up modals + Modal.closeCurrentModal("force"); + }); + + beforeAll(() => { + jest.useFakeTimers(); + }); + + afterAll(() => { + jest.useRealTimers(); + }); + + describe("when starting a password reset flow", () => { + beforeEach(() => { + renderResult = render(); + }); + + it("should show the email input and mention the homeserver", () => { + expect(screen.queryByLabelText("Email address")).toBeInTheDocument(); + expect(screen.queryByText("example.com")).toBeInTheDocument(); + }); + + describe("and updating the server config", () => { + beforeEach(() => { + serverConfig.hsName = "example2.com"; + renderResult.rerender(); + }); + + it("should show the new homeserver server name", () => { + expect(screen.queryByText("example2.com")).toBeInTheDocument(); + }); + }); + + describe("when entering a non-email value", () => { + beforeEach(async () => { + await typeIntoField("Email address", "not en email"); + }); + + it("should show a message about the wrong format", () => { + expect(screen.getByText("The email address doesn't appear to be valid.")).toBeInTheDocument(); + }); + }); + + describe("when submitting an unknown email", () => { + beforeEach(async () => { + await typeIntoField("Email address", testEmail); + mocked(client).requestPasswordEmailToken.mockRejectedValue({ + errcode: "M_THREEPID_NOT_FOUND", + }); + await submitForm("Send email"); + }); + + it("should show an email not found message", () => { + expect(screen.getByText("This email address was not found")).toBeInTheDocument(); + }); + }); + + describe("when a connection error occurs", () => { + beforeEach(async () => { + await typeIntoField("Email address", testEmail); + mocked(client).requestPasswordEmailToken.mockRejectedValue({ + name: "ConnectionError", + }); + await submitForm("Send email"); + }); + + it("should show an info about that", () => { + expect(screen.getByText( + "Cannot reach homeserver: " + + "Ensure you have a stable internet connection, or get in touch with the server admin", + )).toBeInTheDocument(); + }); + }); + + describe("when the server liveness check fails", () => { + beforeEach(async () => { + await typeIntoField("Email address", testEmail); + mocked(AutoDiscoveryUtils.validateServerConfigWithStaticUrls).mockRejectedValue({}); + mocked(AutoDiscoveryUtils.authComponentStateForError).mockReturnValue({ + serverErrorIsFatal: true, + serverIsAlive: false, + serverDeadError: "server down", + }); + await submitForm("Send email"); + }); + + it("should show the server error", () => { + expect(screen.queryByText("server down")).toBeInTheDocument(); + }); + }); + + describe("when submitting an known email", () => { + beforeEach(async () => { + await typeIntoField("Email address", testEmail); + mocked(client).requestPasswordEmailToken.mockResolvedValue({ + sid: testSid, + }); + await submitForm("Send email"); + }); + + it("should send the mail and show the check email view", () => { + expect(client.requestPasswordEmailToken).toHaveBeenCalledWith( + testEmail, + expect.any(String), + 1, // second send attempt + ); + expect(screen.getByText("Check your email to continue")).toBeInTheDocument(); + expect(screen.getByText(testEmail)).toBeInTheDocument(); + }); + + describe("when clicking resend email", () => { + beforeEach(async () => { + await userEvent.click(screen.getByText("Resend"), { delay: null }); + // the message is shown after some time + jest.advanceTimersByTime(500); + }); + + it("should should resend the mail and show the tooltip", () => { + expect(client.requestPasswordEmailToken).toHaveBeenCalledWith( + testEmail, + expect.any(String), + 2, // second send attempt + ); + expect(screen.getByText("Verification link email resent!")).toBeInTheDocument(); + }); + }); + + describe("when clicking next", () => { + beforeEach(async () => { + await submitForm("Next"); + }); + + it("should show the password input view", () => { + expect(screen.getByText("Reset your password")).toBeInTheDocument(); + }); + + describe("when entering different passwords", () => { + beforeEach(async () => { + await typeIntoField("New Password", testPassword); + await typeIntoField("Confirm new password", testPassword + "asd"); + }); + + it("should show an info about that", () => { + expect(screen.getByText("New passwords must match each other.")).toBeInTheDocument(); + }); + }); + + describe("when entering a new password", () => { + beforeEach(async () => { + mocked(client.setPassword).mockRejectedValue({ httpStatus: 401 }); + await typeIntoField("New Password", testPassword); + await typeIntoField("Confirm new password", testPassword); + }); + + describe("and submitting it running into rate limiting", () => { + beforeEach(async () => { + mocked(client.setPassword).mockRejectedValue({ + message: "rate limit reached", + httpStatus: 429, + data: { + retry_after_ms: (13 * 60 + 37) * 1000, + }, + }); + await submitForm("Reset password"); + }); + + it("should show the rate limit error message", () => { + expect( + screen.getByText("Too many attempts in a short time. Retry after 13:37."), + ).toBeInTheDocument(); + }); + }); + + describe("and submitting it", () => { + beforeEach(async () => { + await submitForm("Reset password"); + // double flush promises for the modal to appear + await flushPromisesWithFakeTimers(); + await flushPromisesWithFakeTimers(); + }); + + it("should send the new password and show the click validation link dialog", () => { + expect(client.setPassword).toHaveBeenCalledWith( + { + type: "m.login.email.identity", + threepid_creds: { + client_secret: expect.any(String), + sid: testSid, + }, + threepidCreds: { + client_secret: expect.any(String), + sid: testSid, + }, + }, + testPassword, + false, + ); + expect(screen.getByText("Verify your email to continue")).toBeInTheDocument(); + expect(screen.getByText(testEmail)).toBeInTheDocument(); + }); + + describe("when validating the link from the mail", () => { + beforeEach(async () => { + mocked(client.setPassword).mockResolvedValue({}); + // be sure the next set password attempt was sent + jest.advanceTimersByTime(3000); + // quad flush promises for the modal to disappear + await flushPromisesWithFakeTimers(); + await flushPromisesWithFakeTimers(); + await flushPromisesWithFakeTimers(); + await flushPromisesWithFakeTimers(); + }); + + it("should display the confirm reset view and now show the dialog", () => { + expect(screen.queryByText("Your password has been reset.")).toBeInTheDocument(); + expect(screen.queryByText("Verify your email to continue")).not.toBeInTheDocument(); + }); + }); + }); + }); + }); + }); }); }); diff --git a/test/test-utils/test-utils.ts b/test/test-utils/test-utils.ts index 5b75d87a53..8b4ca9ba86 100644 --- a/test/test-utils/test-utils.ts +++ b/test/test-utils/test-utils.ts @@ -85,6 +85,7 @@ export function createTestClient(): MatrixClient { getIdentityServerUrl: jest.fn(), getDomain: jest.fn().mockReturnValue("matrix.org"), getUserId: jest.fn().mockReturnValue("@userId:matrix.org"), + getUserIdLocalpart: jest.fn().mockResolvedValue("userId"), getUser: jest.fn().mockReturnValue({ on: jest.fn() }), getDeviceId: jest.fn().mockReturnValue("ABCDEFGHI"), deviceId: "ABCDEFGHI", @@ -193,6 +194,9 @@ export function createTestClient(): MatrixClient { uploadContent: jest.fn(), getEventMapper: () => (opts) => new MatrixEvent(opts), leaveRoomChain: jest.fn(roomId => ({ [roomId]: null })), + doesServerSupportLogoutDevices: jest.fn().mockReturnValue(true), + requestPasswordEmailToken: jest.fn().mockRejectedValue({}), + setPassword: jest.fn().mockRejectedValue({}), } as unknown as MatrixClient; client.reEmitter = new ReEmitter(client);