/* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd 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 PropTypes from 'prop-types'; import sdk from '../../../index'; import Email from '../../../email'; import { looksValid as phoneNumberLooksValid } from '../../../phonenumber'; import Modal from '../../../Modal'; import { _t } from '../../../languageHandler'; import SdkConfig from '../../../SdkConfig'; import { SAFE_LOCALPART_REGEX } from '../../../Registration'; import withValidation from '../elements/Validation'; const FIELD_EMAIL = 'field_email'; const FIELD_PHONE_NUMBER = 'field_phone_number'; const FIELD_USERNAME = 'field_username'; const FIELD_PASSWORD = 'field_password'; const FIELD_PASSWORD_CONFIRM = 'field_password_confirm'; /** * A pure UI component which displays a registration form. */ module.exports = React.createClass({ displayName: 'RegistrationForm', propTypes: { // Values pre-filled in the input boxes when the component loads defaultEmail: PropTypes.string, defaultPhoneCountry: PropTypes.string, defaultPhoneNumber: PropTypes.string, defaultUsername: PropTypes.string, defaultPassword: PropTypes.string, minPasswordLength: PropTypes.number, onValidationChange: PropTypes.func, onRegisterClick: PropTypes.func.isRequired, // onRegisterClick(Object) => ?Promise onEditServerDetailsClick: PropTypes.func, flows: PropTypes.arrayOf(PropTypes.object).isRequired, // This is optional and only set if we used a server name to determine // the HS URL via `.well-known` discovery. The server name is used // instead of the HS URL when talking about "your account". hsName: PropTypes.string, hsUrl: PropTypes.string, }, getDefaultProps: function() { return { minPasswordLength: 6, onValidationChange: console.error, }; }, getInitialState: function() { return { // Field error codes by field ID // TODO: Remove `fieldErrors` once converted to new-style validation fieldErrors: {}, fieldValid: {}, // The ISO2 country code selected in the phone number entry phoneCountry: this.props.defaultPhoneCountry, username: "", email: "", phoneNumber: "", password: "", passwordConfirm: "", }; }, onSubmit: function(ev) { ev.preventDefault(); // validate everything, in reverse order so // the error that ends up being displayed // is the one from the first invalid field. // It's not super ideal that this just calls // onValidationChange once for each invalid field. // TODO: Remove these calls once converted to new-style validation. this.validateField(FIELD_PHONE_NUMBER, ev.type); this.validateField(FIELD_PASSWORD_CONFIRM, ev.type); this.validateField(FIELD_PASSWORD, ev.type); const allFieldsValid = this.verifyFieldsBeforeSubmit(); if (!allFieldsValid) { return; } const self = this; if (this.state.email == '') { const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); Modal.createTrackedDialog('If you don\'t specify an email address...', '', QuestionDialog, { title: _t("Warning!"), description:
{ _t("If you don't specify an email address, you won't be able to reset your password. " + "Are you sure?") }
, button: _t("Continue"), onFinished: function(confirmed) { if (confirmed) { self._doSubmit(ev); } }, }); } else { self._doSubmit(ev); } }, _doSubmit: function(ev) { const email = this.state.email.trim(); const promise = this.props.onRegisterClick({ username: this.state.username.trim(), password: this.state.password.trim(), email: email, phoneCountry: this.state.phoneCountry, phoneNumber: this.state.phoneNumber, }); if (promise) { ev.target.disabled = true; promise.finally(function() { ev.target.disabled = false; }); } }, verifyFieldsBeforeSubmit() { const fieldIDsInDisplayOrder = [ FIELD_USERNAME, FIELD_PASSWORD, FIELD_PASSWORD_CONFIRM, FIELD_EMAIL, FIELD_PHONE_NUMBER, ]; // Run all fields with stricter validation that no longer allows empty // values for required fields. for (const fieldID of fieldIDsInDisplayOrder) { const field = this[fieldID]; if (!field) { continue; } field.validate({ allowEmpty: false }); } if (this.allFieldsValid()) { return true; } const invalidField = this.findFirstInvalidField(fieldIDsInDisplayOrder); if (!invalidField) { return true; } // Focus the first invalid field and show feedback in the stricter mode // that no longer allows empty values for required fields. invalidField.focus(); invalidField.validate({ allowEmpty: false, focused: true }); return false; }, /** * @returns {boolean} true if all fields were valid last time they were validated. */ allFieldsValid: function() { // TODO: Remove `fieldErrors` here when all fields converted let keys = Object.keys(this.state.fieldErrors); for (let i = 0; i < keys.length; ++i) { if (this.state.fieldErrors[keys[i]]) { return false; } } keys = Object.keys(this.state.fieldValid); for (let i = 0; i < keys.length; ++i) { if (!this.state.fieldValid[keys[i]]) { return false; } } return true; }, findFirstInvalidField(fieldIDs) { for (const fieldID of fieldIDs) { if (!this.state.fieldValid[fieldID] && this[fieldID]) { return this[fieldID]; } } return null; }, validateField: function(fieldID, eventType) { const pwd1 = this.state.password.trim(); const pwd2 = this.state.passwordConfirm.trim(); const allowEmpty = eventType === "blur"; // TODO: Remove rules here as they are converted to new-style validation switch (fieldID) { case FIELD_PHONE_NUMBER: { const phoneNumber = this.state.phoneNumber; const phoneNumberValid = phoneNumber === '' || phoneNumberLooksValid(phoneNumber); if (this._authStepIsRequired('m.login.msisdn') && (!phoneNumberValid || phoneNumber === '')) { this.markFieldError(fieldID, false, "RegistrationForm.ERR_MISSING_PHONE_NUMBER"); } else this.markFieldError(fieldID, phoneNumberValid, "RegistrationForm.ERR_PHONE_NUMBER_INVALID"); break; } case FIELD_PASSWORD: if (allowEmpty && pwd1 === "") { this.markFieldError(fieldID, true); } else if (pwd1 == '') { this.markFieldError( fieldID, false, "RegistrationForm.ERR_PASSWORD_MISSING", ); } else if (pwd1.length < this.props.minPasswordLength) { this.markFieldError( fieldID, false, "RegistrationForm.ERR_PASSWORD_LENGTH", ); } else { this.markFieldError(fieldID, true); } break; case FIELD_PASSWORD_CONFIRM: if (allowEmpty && pwd2 === "") { this.markFieldError(fieldID, true); } else { this.markFieldError( fieldID, pwd1 == pwd2, "RegistrationForm.ERR_PASSWORD_MISMATCH", ); } break; } }, markFieldError: function(fieldID, valid, errorCode) { // TODO: Remove this function once all fields converted to new-style validation. const { fieldErrors } = this.state; if (valid) { fieldErrors[fieldID] = null; } else { fieldErrors[fieldID] = errorCode; } this.setState({ fieldErrors, }); // TODO: Remove outer validation handling once all fields converted to new-style // validation in the form. this.props.onValidationChange(fieldErrors); }, markFieldValid: function(fieldID, valid) { const { fieldValid } = this.state; fieldValid[fieldID] = valid; this.setState({ fieldValid, }); }, _classForField: function(fieldID, ...baseClasses) { let cls = baseClasses.join(' '); // TODO: Remove this from fields as they are converted to new-style validation. if (this.state.fieldErrors[fieldID]) { if (cls) cls += ' '; cls += 'error'; } return cls; }, onEmailChange(ev) { this.setState({ email: ev.target.value, }); }, onEmailValidate(fieldState) { const result = this.validateEmailRules(fieldState); this.markFieldValid(FIELD_EMAIL, result.valid); return result; }, validateEmailRules: withValidation({ description: () => _t("Use an email address to recover your account"), rules: [ { key: "required", test: function({ value, allowEmpty }) { return allowEmpty || !this._authStepIsRequired('m.login.email.identity') || !!value; }, invalid: () => _t("Enter email address (required on this homeserver)"), }, { key: "email", test: ({ value }) => !value || Email.looksValid(value), invalid: () => _t("Doesn't look like a valid email address"), }, ], }), onPasswordBlur(ev) { this.validateField(FIELD_PASSWORD, ev.type); }, onPasswordChange(ev) { this.setState({ password: ev.target.value, }); }, onPasswordConfirmBlur(ev) { this.validateField(FIELD_PASSWORD_CONFIRM, ev.type); }, onPasswordConfirmChange(ev) { this.setState({ passwordConfirm: ev.target.value, }); }, onPhoneCountryChange(newVal) { this.setState({ phoneCountry: newVal.iso2, phonePrefix: newVal.prefix, }); }, onPhoneNumberBlur(ev) { this.validateField(FIELD_PHONE_NUMBER, ev.type); }, onPhoneNumberChange(ev) { this.setState({ phoneNumber: ev.target.value, }); }, onUsernameChange(ev) { this.setState({ username: ev.target.value, }); }, onUsernameValidate(fieldState) { const result = this.validateUsernameRules(fieldState); this.markFieldValid(FIELD_USERNAME, result.valid); return result; }, validateUsernameRules: withValidation({ description: () => _t("Use letters, numbers, dashes and underscores only"), rules: [ { key: "required", test: ({ value, allowEmpty }) => allowEmpty || !!value, invalid: () => _t("Enter username"), }, { key: "safeLocalpart", test: ({ value }) => !value || SAFE_LOCALPART_REGEX.test(value), invalid: () => _t("Some characters not allowed"), }, ], }), /** * A step is required if all flows include that step. * * @param {string} step A stage name to check * @returns {boolean} Whether it is required */ _authStepIsRequired(step) { return this.props.flows.every((flow) => { return flow.stages.includes(step); }); }, /** * A step is used if any flows include that step. * * @param {string} step A stage name to check * @returns {boolean} Whether it is used */ _authStepIsUsed(step) { return this.props.flows.some((flow) => { return flow.stages.includes(step); }); }, renderEmail() { if (!this._authStepIsUsed('m.login.email.identity')) { return null; } const Field = sdk.getComponent('elements.Field'); const emailPlaceholder = this._authStepIsRequired('m.login.email.identity') ? _t("Email") : _t("Email (optional)"); return this[FIELD_EMAIL] = field} type="text" label={emailPlaceholder} defaultValue={this.props.defaultEmail} value={this.state.email} onChange={this.onEmailChange} onValidate={this.onEmailValidate} />; }, renderUsername() { const Field = sdk.getComponent('elements.Field'); return this[FIELD_USERNAME] = field} type="text" autoFocus={true} label={_t("Username")} defaultValue={this.props.defaultUsername} value={this.state.username} onChange={this.onUsernameChange} onValidate={this.onUsernameValidate} />; }, render: function() { const Field = sdk.getComponent('elements.Field'); let yourMatrixAccountText = _t('Create your Matrix account'); if (this.props.hsName) { yourMatrixAccountText = _t('Create your Matrix account on %(serverName)s', { serverName: this.props.hsName, }); } else { try { const parsedHsUrl = new URL(this.props.hsUrl); yourMatrixAccountText = _t('Create your Matrix account on %(serverName)s', { serverName: parsedHsUrl.hostname, }); } catch (e) { // ignore } } let editLink = null; if (this.props.onEditServerDetailsClick) { editLink = {_t('Change')} ; } const threePidLogin = !SdkConfig.get().disable_3pid_login; const CountryDropdown = sdk.getComponent('views.auth.CountryDropdown'); let phoneSection; if (threePidLogin && this._authStepIsUsed('m.login.msisdn')) { const phoneLabel = this._authStepIsRequired('m.login.msisdn') ? _t("Phone") : _t("Phone (optional)"); const phoneCountry = ; phoneSection = ; } const registerButton = ( ); return (

{yourMatrixAccountText} {editLink}

{this.renderUsername()}
{this.renderEmail()} { phoneSection }
{_t("Use an email address to recover your account.") + " "} {_t("Other users can invite you to rooms using your contact details.")} { registerButton }
); }, });