import config from '@automattic/calypso-config'; import page from '@automattic/calypso-router'; import { Gridicon, FormLabel } from '@automattic/components'; import { addLocaleToPath, localizeUrl, getLanguage } from '@automattic/i18n-utils'; import clsx from 'clsx'; import emailValidator from 'email-validator'; import { localize, fixMe } from 'i18n-calypso'; import PropTypes from 'prop-types'; import { Component } from 'react'; import { connect } from 'react-redux'; import AppPromo from 'calypso/blocks/app-promo'; import { shouldUseMagicCode } from 'calypso/blocks/login/utils/should-use-magic-code'; import FormButton from 'calypso/components/forms/form-button'; import FormTextInput from 'calypso/components/forms/form-text-input'; import GlobalNotices from 'calypso/components/global-notices'; import GravatarLoginLogo from 'calypso/components/gravatar-login-logo'; import LocaleSuggestions from 'calypso/components/locale-suggestions'; import Main from 'calypso/components/main'; import Notice from 'calypso/components/notice'; import isAkismetRedirect from 'calypso/lib/akismet/is-akismet-redirect'; import getGravatarOAuth2Flow from 'calypso/lib/get-gravatar-oauth2-flow'; import { isGravatarFlowOAuth2Client, isGravatarOAuth2Client, isWPJobManagerOAuth2Client, isGravPoweredOAuth2Client, isStudioAppOAuth2Client, } from 'calypso/lib/oauth2-clients'; import { login } from 'calypso/lib/paths'; import getToSAcceptancePayload from 'calypso/lib/tos-acceptance-tracking'; import wpcom from 'calypso/lib/wp'; import OneLoginLayout from 'calypso/login/wp-login/components/one-login-layout'; import { recordTracksEventWithClientId as recordTracksEvent, recordPageViewWithClientId as recordPageView, enhanceWithSiteType, } from 'calypso/state/analytics/actions'; import { sendEmailLogin } from 'calypso/state/auth/actions'; import { rebootAfterLogin } from 'calypso/state/login/actions'; import { hideMagicLoginRequestForm, fetchMagicLoginAuthenticate, } from 'calypso/state/login/magic-login/actions'; import { CHECK_YOUR_EMAIL_PAGE } from 'calypso/state/login/magic-login/constants'; import { getLastCheckedUsernameOrEmail, getTwoFactorNotificationSent, isTwoFactorEnabled, getRedirectToSanitized, getRedirectToOriginal, } from 'calypso/state/login/selectors'; import { infoNotice, errorNotice, successNotice, removeNotice, } from 'calypso/state/notices/actions'; import { getCurrentOAuth2Client } from 'calypso/state/oauth2-clients/ui/selectors'; import getCurrentLocaleSlug from 'calypso/state/selectors/get-current-locale-slug'; import getCurrentQueryArguments from 'calypso/state/selectors/get-current-query-arguments'; import { getCurrentRoute } from 'calypso/state/selectors/get-current-route'; import getInitialQueryArguments from 'calypso/state/selectors/get-initial-query-arguments'; import getIsWCCOM from 'calypso/state/selectors/get-is-wccom'; import getLocaleSuggestions from 'calypso/state/selectors/get-locale-suggestions'; import getMagicLoginCurrentView from 'calypso/state/selectors/get-magic-login-current-view'; import getMagicLoginPublicToken from 'calypso/state/selectors/get-magic-login-public-token'; import getMagicLoginRequestAuthError from 'calypso/state/selectors/get-magic-login-request-auth-error'; import getMagicLoginRequestEmailError from 'calypso/state/selectors/get-magic-login-request-email-error'; import getMagicLoginRequestedAuthSuccessfully from 'calypso/state/selectors/get-magic-login-requested-auth-successfully'; import isFetchingMagicLoginAuth from 'calypso/state/selectors/is-fetching-magic-login-auth'; import isFetchingMagicLoginEmail from 'calypso/state/selectors/is-fetching-magic-login-email'; import isMagicLoginEmailRequested from 'calypso/state/selectors/is-magic-login-email-requested'; import isWooJPCFlow from 'calypso/state/selectors/is-woo-jpc-flow'; import { withEnhancers } from 'calypso/state/utils'; import MainContentWooCoreProfiler from './main-content-woo-core-profiler'; import RequestLoginCode from './request-login-code'; import RequestLoginEmailForm from './request-login-email-form'; import './style.scss'; const RESEND_EMAIL_COUNTDOWN_TIME = 90; // In seconds const GRAVATAR_FROM_3RD_PARTY = '3rd-party'; const GRAVATAR_FROM_QUICK_EDITOR = 'quick-editor'; class MagicLogin extends Component { static propTypes = { path: PropTypes.string.isRequired, // mapped to dispatch hideMagicLoginRequestForm: PropTypes.func.isRequired, recordPageView: PropTypes.func.isRequired, recordTracksEvent: PropTypes.func.isRequired, sendEmailLogin: PropTypes.func.isRequired, fetchMagicLoginAuthenticate: PropTypes.func.isRequired, infoNotice: PropTypes.func.isRequired, errorNotice: PropTypes.func.isRequired, successNotice: PropTypes.func.isRequired, removeNotice: PropTypes.func.isRequired, rebootAfterLogin: PropTypes.func.isRequired, // mapped to state locale: PropTypes.string.isRequired, query: PropTypes.object, showCheckYourEmail: PropTypes.bool.isRequired, isSendingEmail: PropTypes.bool.isRequired, emailRequested: PropTypes.bool.isRequired, localeSuggestions: PropTypes.array, isValidatingCode: PropTypes.bool, isCodeValidated: PropTypes.bool, codeValidationError: PropTypes.object, twoFactorEnabled: PropTypes.bool, twoFactorNotificationSent: PropTypes.string, redirectToSanitized: PropTypes.string, // From `localize` translate: PropTypes.func.isRequired, isWooJPC: PropTypes.bool, }; state = { usernameOrEmail: this.props.userEmail || '', resendEmailCountdown: RESEND_EMAIL_COUNTDOWN_TIME, verificationCodeInputValue: '', isRequestingEmail: false, requestEmailErrorMessage: null, isSecondaryEmail: false, isNewAccount: false, publicToken: null, showSecondaryEmailOptions: false, showEmailCodeVerification: false, maskedEmailAddress: '', hashedEmail: null, }; componentDidMount() { const { oauth2Client, query } = this.props; this.props.recordPageView( '/log-in/link', 'Login > Link' ); if ( isGravPoweredOAuth2Client( oauth2Client ) ) { const isGravatarFlow = isGravatarFlowOAuth2Client( oauth2Client ); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_form', { client_id: oauth2Client.id, client_name: oauth2Client.title, from: query?.gravatar_from, is_gravatar_flow: isGravatarFlow, is_gravatar_flow_with_email: !! ( isGravatarFlow && query?.email_address ), is_initial_view: true, } ); } } componentDidUpdate( prevProps, prevState ) { const { oauth2Client, emailRequested, emailRequestError, localeSuggestions, path, showCheckYourEmail, isCodeValidated, twoFactorEnabled, twoFactorNotificationSent, redirectToSanitized, query, } = this.props; const { showSecondaryEmailOptions, showEmailCodeVerification } = this.state; /** * If the user is not allowed to use magic links and we have auto trigger enabled, * we simply show the password login form. * * If we don't check for auto trigger here, the normal wp.com login flow will confuse the users * when they land here without the auto trigger, i.e. when they click on "Email me a login link" * at wp.com/log-in */ if ( 'login_link_not_allowed' === emailRequestError?.code && query?.auto_trigger ) { this.onClickEnterPasswordInstead(); } if ( isGravPoweredOAuth2Client( oauth2Client ) ) { if ( prevProps.isSendingEmail && emailRequested ) { this.startResendEmailCountdown(); } if ( ! prevProps.localeSuggestions && localeSuggestions ) { const userLocale = localeSuggestions.find( ( { locale } ) => locale === navigator.language.toLowerCase() ); if ( userLocale ) { page( addLocaleToPath( path, userLocale.locale ) ); } } const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title }; if ( ( prevProps.showCheckYourEmail && ! showCheckYourEmail ) || ( prevState.showEmailCodeVerification && ! showEmailCodeVerification ) || ( prevState.showSecondaryEmailOptions && ! showSecondaryEmailOptions ) ) { const isGravatarFlow = isGravatarFlowOAuth2Client( oauth2Client ); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_form', { ...eventOptions, from: query?.gravatar_from, is_gravatar_flow: isGravatarFlow, is_gravatar_flow_with_email: !! ( isGravatarFlow && query?.email_address ), is_initial_view: false, } ); } if ( ! prevState.showSecondaryEmailOptions && showSecondaryEmailOptions ) { this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_secondary_email_options', eventOptions ); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_click_main_account', eventOptions ); } if ( ! prevState.showEmailCodeVerification && showEmailCodeVerification ) { this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_code_verification', eventOptions ); } if ( ! prevProps.showCheckYourEmail && showCheckYourEmail ) { this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_link_verification', eventOptions ); } // Proceed to the next step if the magic code is validated. if ( ! prevProps.isCodeValidated && isCodeValidated ) { if ( ! twoFactorEnabled ) { this.props.rebootAfterLogin( { magic_login: 1 } ); } else { page( login( { // If no notification is sent, the user is using the authenticator for 2FA by default. twoFactorAuthType: twoFactorNotificationSent.replace( 'none', 'authenticator' ), redirectTo: redirectToSanitized, oauth2ClientId: oauth2Client.id, locale: this.props.locale, } ) ); } } } } onClickEnterPasswordInstead = ( event ) => { event?.preventDefault(); this.props.recordTracksEvent( 'calypso_login_email_link_page_click_back' ); const loginParameters = { isJetpack: this.props.isJetpackLogin, locale: this.props.locale, emailAddress: this.props.userEmail, signupUrl: this.props.query?.signup_url, usernameOnly: true, twoFactorAuthType: this.props.twoFactorNotificationSent?.replace( 'none', 'authenticator' ), redirectTo: this.props.redirectToOriginal, oauth2ClientId: this.props.oauth2Client?.id, from: this.props.query?.from, }; page( login( loginParameters ) ); }; renderLinks() { const { isJetpackLogin, locale, showCheckYourEmail, translate, query, twoFactorNotificationSent, redirectToSanitized, oauth2Client, } = this.props; const isA4A = query?.redirect_to?.includes( 'agencies.automattic.com/client' ) ?? false; if ( showCheckYourEmail ) { if ( isA4A ) { return null; } return ( ); } // The email address from the URL (if present) is added to the login // parameters in this.onClickEnterPasswordInstead(). But it's left out // here deliberately, to ensure that if someone copies this link to // paste somewhere else, their email address isn't included in it. const loginParameters = { isJetpack: isJetpackLogin, locale: locale, signupUrl: query?.signup_url, twoFactorAuthType: twoFactorNotificationSent?.replace( 'none', 'authenticator' ), redirectTo: redirectToSanitized, oauth2ClientId: oauth2Client?.id, from: query?.from, }; let linkBack = translate( 'Enter a password instead' ); if ( query?.username_only === 'true' ) { linkBack = translate( 'Use username and password instead' ); } return ( <>
{ linkBack }
{ ! oauth2Client && ( ) } ); } renderLocaleSuggestions() { const { locale, path, showCheckYourEmail } = this.props; if ( showCheckYourEmail ) { return null; } return ; } handleGravPoweredEmailCodeSend = async ( email, cb = () => {} ) => { const { oauth2Client, query, locale, translate } = this.props; const { isSecondaryEmail, isNewAccount } = this.state; const noticeId = 'email-code-notice'; const duration = 4000; const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title }; this.setState( { isRequestingEmail: true } ); try { this.props.infoNotice( translate( 'Sending email…' ), { id: noticeId, duration } ); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_code_requesting', eventOptions ); const { public_token } = await wpcom.req.post( '/auth/send-login-email', { apiVersion: '1.3' }, { client_id: config( 'wpcom_signup_id' ), client_secret: config( 'wpcom_signup_key' ), locale, lang_id: getLanguage( locale ).value, email, redirect_to: query?.redirect_to, flow: getGravatarOAuth2Flow( oauth2Client ), create_account: true, tos: getToSAcceptancePayload(), token_type: 'code', ...( isSecondaryEmail ? { gravatar_main: ! isNewAccount } : {} ), } ); this.setState( { publicToken: public_token, showEmailCodeVerification: true } ); this.startResendEmailCountdown(); cb(); this.props.removeNotice( noticeId ); this.props.successNotice( translate( 'Email Sent. Check your mail app!' ), { duration } ); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_code_success', eventOptions ); } catch ( error ) { if ( error.error ) { this.setState( { requestEmailErrorMessage: error.message } ); } else { this.setState( { requestEmailErrorMessage: translate( 'Something went wrong. Please try again.' ), } ); } this.props.removeNotice( noticeId ); this.props.errorNotice( translate( 'Sorry, we couldn’t send the email.' ), { duration } ); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_email_code_failure', { ...eventOptions, error_code: error.status, error_message: error.message, } ); } this.setState( { isRequestingEmail: false } ); }; handleGravPoweredEmailSubmit = async ( usernameOrEmail, e ) => { e.preventDefault(); const { translate, oauth2Client } = this.props; const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title }; if ( ! emailValidator.validate( usernameOrEmail ) ) { return this.setState( { requestEmailErrorMessage: translate( 'Invalid email.' ) } ); } this.setState( { usernameOrEmail, isRequestingEmail: true } ); try { this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_gravatar_info_fetching', eventOptions ); const { is_secondary, main_email_masked } = await wpcom.req.get( '/auth/get-gravatar-info', { email: usernameOrEmail, } ); if ( is_secondary ) { this.setState( { usernameOrEmail, isSecondaryEmail: true, showSecondaryEmailOptions: true, maskedEmailAddress: main_email_masked, isRequestingEmail: false, } ); } else { this.handleGravPoweredEmailCodeSend( usernameOrEmail ); } this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_gravatar_info_success', eventOptions ); } catch ( error ) { switch ( error.error ) { case 'not_found': this.setState( { isNewAccount: true } ); this.handleGravPoweredEmailCodeSend( usernameOrEmail ); break; case 'invalid_email': this.setState( { requestEmailErrorMessage: translate( 'Invalid email.' ), isRequestingEmail: false, } ); break; default: this.setState( { requestEmailErrorMessage: translate( 'Something went wrong. Please try again.' ), isRequestingEmail: false, } ); } this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_gravatar_info_failure', { ...eventOptions, error_code: error.status, error_message: error.message, } ); } }; handleGravPoweredCodeInputChange = ( e ) => { let value = e.target.value.toUpperCase(); if ( ! /^[A-Z0-9]*$/.test( value ) || value.length > 6 ) { value = this.state.verificationCodeInputValue; } this.setState( { verificationCodeInputValue: value } ); }; handleGravPoweredCodeSubmit = ( e ) => { e.preventDefault(); const { oauth2Client, query } = this.props; const { publicToken, verificationCodeInputValue } = this.state; this.props.fetchMagicLoginAuthenticate( `${ publicToken }:${ btoa( verificationCodeInputValue ) }`, query?.redirect_to, getGravatarOAuth2Flow( oauth2Client ), true ); }; handleGravPoweredEmailSwitch = () => { const { oauth2Client, hideMagicLoginRequestForm: showEmailForm } = this.props; this.setState( { showSecondaryEmailOptions: false, showEmailCodeVerification: false, verificationCodeInputValue: '', isNewAccount: false, } ); showEmailForm(); this.props.recordTracksEvent( 'calypso_gravatar_powered_magic_login_click_switch_email', { client_id: oauth2Client.id, client_name: oauth2Client.title, } ); }; renderGravPoweredMagicLoginTos() { const { oauth2Client, translate } = this.props; const textOptions = { components: { tosLink: ( ), privacyLink: ( ), wpAccountLink: ( ), }, }; return (
{ isGravatarOAuth2Client( oauth2Client ) ? translate( `By clicking “Continue“, you agree to our {{tosLink}}Terms of Service{{/tosLink}}, have read our {{privacyLink}}Privacy Policy{{/privacyLink}}, and understand that you're creating {{wpAccountLink}}a WordPress.com account{{/wpAccountLink}} if you don't already have one.`, textOptions ) : translate( `By clicking “Send me sign in link“, you agree to our {{tosLink}}Terms of Service{{/tosLink}}, have read our {{privacyLink}}Privacy Policy{{/privacyLink}}, and understand that you're creating a Gravatar account if you don't already have one.`, textOptions ) }
); } resendEmailCountdownId = null; resetResendEmailCountdown = () => { if ( ! this.resendEmailCountdownId ) { return; } clearInterval( this.resendEmailCountdownId ); this.resendEmailCountdownId = null; this.setState( { resendEmailCountdown: RESEND_EMAIL_COUNTDOWN_TIME } ); }; startResendEmailCountdown = () => { this.resetResendEmailCountdown(); this.resendEmailCountdownId = setInterval( () => { if ( ! this.state.resendEmailCountdown ) { clearInterval( this.resendEmailCountdownId ); return; } this.setState( ( prevState ) => ( { resendEmailCountdown: prevState.resendEmailCountdown - 1, } ) ); }, 1000 ); }; emailToSha256 = async ( email ) => { if ( ! window.crypto?.subtle ) { return null; } const data = new TextEncoder().encode( email ); const hashBuffer = await crypto.subtle.digest( 'SHA-256', data ); return Array.from( new Uint8Array( hashBuffer ) ) .map( ( byte ) => byte.toString( 16 ).padStart( 2, '0' ) ) .join( '' ); }; renderGravPoweredLogo() { const { oauth2Client } = this.props; return ( ); } renderGravPoweredSecondaryEmailOptions() { const { oauth2Client, translate, query } = this.props; const { usernameOrEmail, isNewAccount, maskedEmailAddress, isRequestingEmail, requestEmailErrorMessage, hashedEmail, } = this.state; const eventOptions = { client_id: oauth2Client.id, client_name: oauth2Client.title }; const isFromGravatar3rdPartyApp = isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY; const isFromGravatarQuickEditor = isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR; const isGravatarFlowWithEmail = !! ( isGravatarFlowOAuth2Client( oauth2Client ) && query?.email_address ); const shouldShowSwitchEmail = ! isFromGravatar3rdPartyApp && ! isFromGravatarQuickEditor && ! isGravatarFlowWithEmail; this.emailToSha256( usernameOrEmail ).then( ( email ) => this.setState( { hashedEmail: email } ) ); return (
{ this.renderGravPoweredLogo() }

{ translate( 'Important note' ) }

{ translate( 'The submitted email is already linked to an existing Gravatar account as a secondary email:' ) }

{ translate( 'Account: {{strong}}%(maskedEmailAddress)s{{/strong}}', { components: { strong: }, args: { maskedEmailAddress }, } ) }
{ hashedEmail && (
{ translate( 'Open profile' ) } ) }
{ ! isNewAccount && (
{ translate( 'Log in with your main account and edit there your avatar for your secondary email address.' ) }
) } { isNewAccount && (
{ translate( 'If you continue a new account will be created, and {{strong}}%(emailAddress)s{{/strong}} will be disconnected from the current main account.', { components: { strong: }, args: { emailAddress: usernameOrEmail }, } ) }
) }
{ requestEmailErrorMessage && ( this.setState( { requestEmailErrorMessage: null } ) } status="is-transparent-info" /> ) } this.handleGravPoweredEmailCodeSend( usernameOrEmail, () => this.setState( { showSecondaryEmailOptions: false } ) ) } disabled={ isRequestingEmail || !! requestEmailErrorMessage } busy={ isRequestingEmail } > { translate( 'Continue' ) }
); } renderGravPoweredEmailCodeVerification() { const { oauth2Client, translate, isValidatingCode, isCodeValidated, codeValidationError, query, } = this.props; const { isSecondaryEmail, isNewAccount, isRequestingEmail, maskedEmailAddress, usernameOrEmail, verificationCodeInputValue, resendEmailCountdown, } = this.state; const isFromGravatar3rdPartyApp = isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY; const isFromGravatarQuickEditor = isGravatarOAuth2Client( oauth2Client ) && query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR; const isGravatarFlowWithEmail = !! ( isGravatarFlowOAuth2Client( oauth2Client ) && query?.email_address ); const shouldShowSwitchEmail = ! isFromGravatar3rdPartyApp && ! isFromGravatarQuickEditor && ! isGravatarFlowWithEmail; const isProcessingCode = isValidatingCode || isCodeValidated; let errorText = translate( 'Something went wrong. Please try again.' ); if ( codeValidationError?.type === 'sms_code_throttled' ) { errorText = translate( 'Your two-factor code via SMS can only be requested once per minute. Please wait, then request a new code via email to proceed.' ); } else if ( codeValidationError?.type === 'user_email' ) { errorText = translate( "We're sorry, you can't create a new account at this time. Please try a different email address or disable any VPN before trying again." ); } else if ( codeValidationError?.code === 403 ) { errorText = translate( 'Invalid code. If the error persists, please request a new code and try again.' ); } else if ( codeValidationError?.code === 429 ) { errorText = translate( 'Please wait a minute before trying again.' ); } return (
{ this.renderGravPoweredLogo() }

{ translate( 'Check your email' ) }

{ translate( 'Enter the verification code we’ve sent to {{strong}}%(emailAddress)s{{/strong}}.', { components: { strong: }, args: { emailAddress: isSecondaryEmail && ! isNewAccount ? maskedEmailAddress : usernameOrEmail, }, } ) } { isSecondaryEmail && isNewAccount && ( { translate( ' A new Gravatar account will be created.' ) } ) } { isSecondaryEmail && ! isNewAccount && ( { translate( ' This email already exists and is synced with Gravatar.' ) } ) }

{ isNewAccount && this.renderGravPoweredMagicLoginTos() }
{ codeValidationError && ( ) } { translate( 'Continue' ) }
{ shouldShowSwitchEmail && ( ) } { translate( 'Need help logging in?' ) }
); } renderGravPoweredEmailLinkVerification() { const { oauth2Client, translate, query, isSendingEmail, sendEmailLogin: resendEmail, } = this.props; const { usernameOrEmail, resendEmailCountdown } = this.state; const emailAddress = usernameOrEmail.includes( '@' ) ? usernameOrEmail : null; const emailTextOptions = { components: { sendEmailButton: (