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 (
<>
{ ! 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' ) }
) }
{
this.setState( { isNewAccount: false } );
this.props.recordTracksEvent(
'calypso_gravatar_powered_magic_login_click_main_account',
eventOptions
);
} }
disabled={ isRequestingEmail }
>
{ translate( 'Log in with main account (recommended)' ) }
{ ! isNewAccount && (
{ translate(
'Log in with your main account and edit there your avatar for your secondary email address.'
) }
) }
{
this.setState( { isNewAccount: true } );
this.props.recordTracksEvent(
'calypso_gravatar_powered_magic_login_click_new_account',
eventOptions
);
} }
disabled={ isRequestingEmail }
>
{ translate( 'Create a new account' ) }
{ 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() }
{
this.handleGravPoweredEmailCodeSend( usernameOrEmail );
this.props.recordTracksEvent(
'calypso_gravatar_powered_magic_login_click_resend_email',
{ type: 'code', client_id: oauth2Client.id, client_name: oauth2Client.title }
);
} }
disabled={ isRequestingEmail || resendEmailCountdown }
>
{ resendEmailCountdown === 0
? translate( 'Send again' )
: translate( 'Send again (%(countdown)d)', {
args: { countdown: resendEmailCountdown },
} ) }
{ shouldShowSwitchEmail && (
{
this.resetResendEmailCountdown();
this.handleGravPoweredEmailSwitch();
} }
>
{ translate( 'Switch email' ) }
) }
{ 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: (
{
resendEmail( usernameOrEmail, {
redirectTo: query?.redirect_to,
requestLoginEmailFormFlow: true,
createAccount: true,
flow: getGravatarOAuth2Flow( oauth2Client ),
showGlobalNotices: true,
} );
this.props.recordTracksEvent(
'calypso_gravatar_powered_magic_login_click_resend_email',
{ type: 'link', client_id: oauth2Client.id, client_name: oauth2Client.title }
);
} }
disabled={ isSendingEmail }
/>
),
showMagicLoginButton: (
{
this.resetResendEmailCountdown();
this.handleGravPoweredEmailSwitch();
} }
/>
),
},
};
return (
{ this.renderGravPoweredLogo() }
{ translate( 'Check your email!' ) }
{ emailAddress
? translate(
"We've sent an email with a verification link to {{strong}}%(emailAddress)s{{/strong}}",
{
components: { strong: },
args: { emailAddress },
}
)
: translate(
'We just emailed you a link. Please check your inbox and click the link to log in.'
) }
{ translate( 'Are you having issues receiving it?' ) }
{ resendEmailCountdown === 0
? translate(
'{{sendEmailButton}}Resend the verification email{{/sendEmailButton}} or {{showMagicLoginButton}}use a different email address{{/showMagicLoginButton}}.',
emailTextOptions
)
: translate(
'{{showMagicLoginButton}}Use a different email address{{/showMagicLoginButton}}.',
emailTextOptions
) }
);
}
renderGravPoweredMagicLogin() {
const { oauth2Client, translate, locale, query } = this.props;
const { isRequestingEmail, requestEmailErrorMessage } = this.state;
const isGravatarFlow = isGravatarFlowOAuth2Client( oauth2Client );
const isGravatarFlowWithEmail = !! ( isGravatarFlow && query?.email_address );
const isGravatar = isGravatarOAuth2Client( oauth2Client );
const isWPJobManager = isWPJobManagerOAuth2Client( oauth2Client );
const isFromGravatarSignup = isGravatar && query?.gravatar_from === 'signup';
const isFromGravatar3rdPartyApp =
isGravatar && query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY;
const isFromGravatarQuickEditor =
isGravatar && query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR;
const isEmailInputDisabled =
isFromGravatar3rdPartyApp ||
isFromGravatarQuickEditor ||
isRequestingEmail ||
isGravatarFlowWithEmail;
const submitButtonLabel = isGravatar
? translate( 'Continue' )
: translate( 'Send me sign in link' );
const loginUrl = login( {
locale,
redirectTo: query?.redirect_to,
oauth2ClientId: query?.client_id,
gravatarFrom: query?.gravatar_from,
gravatarFlow: isGravatarFlow,
emailAddress: query?.email_address,
} );
let headerText = isFromGravatarSignup
? translate( 'Create your Gravatar' )
: translate( 'Edit your Gravatar' );
headerText = isWPJobManager ? translate( 'Sign in with your email' ) : headerText;
let subHeader = '';
if ( isGravatarFlow ) {
subHeader = translate( '%(clientTitle)s profiles are powered by Gravatar.', {
args: { clientTitle: oauth2Client.title },
} );
} else if ( isFromGravatar3rdPartyApp || isFromGravatarQuickEditor ) {
subHeader = translate( 'Profiles and avatars are powered by Gravatar.' );
}
return (
<>
{ this.renderLocaleSuggestions() }
{ this.renderGravPoweredLogo() }
this.setState( { usernameOrEmail } ) }
createAccountForNewUser
errorMessage={ requestEmailErrorMessage }
onErrorDismiss={ () => this.setState( { requestEmailErrorMessage: null } ) }
isEmailInputDisabled={ isEmailInputDisabled }
isEmailInputError={ !! requestEmailErrorMessage }
isSubmitButtonDisabled={ isRequestingEmail || !! requestEmailErrorMessage }
isSubmitButtonBusy={ isRequestingEmail }
/>
{ isGravatar && (
{ translate( 'One profile, everywhere' ) }
{ translate( 'Your avatar and bio syncs across the web.' ) }
{ translate( 'Public, open, and responsible' ) }
{ translate( 'Full control over your data and privacy.' ) }
{ translate( '200+ million users' ) }
{ translate( 'Used by WordPress, Slack, and many more.' ) }
) }
{ isWPJobManager && (
) }
{ ! isFromGravatarSignup && (
) }
{ isWPJobManager && (
{ translate( 'You will be logging in via Gravatar' ) }
{ translate(
'Gravatar accounts and profiles are free. You can log in to thousands of sites across the web with one Gravatar account.'
) }
{ translate( 'Control what information is shared on your public profile.' ) }
{ translate(
"Have questions? Please see Gravatar's {{a}}documentation here{{/a}}.",
{
components: {
a:
,
},
}
) }
) }
>
);
}
renderTos = () => {
const { translate } = this.props;
const options = {
components: {
tosLink: (
),
privacyLink: (
),
},
};
const tosText = fixMe( {
text: 'By continuing you agree to our {{tosLink}}Terms of Service{{/tosLink}} and have read our {{privacyLink}}Privacy Policy{{/privacyLink}}.',
newCopy: translate(
'By continuing you agree to our {{tosLink}}Terms of Service{{/tosLink}} and have read our {{privacyLink}}Privacy Policy{{/privacyLink}}.',
options
),
oldCopy: translate(
'By creating an account you agree to our {{tosLink}}Terms of Service{{/tosLink}} and have read our {{privacyLink}}Privacy Policy{{/privacyLink}}.',
options
),
} );
return { tosText }
;
};
handlePublicTokenReceived = ( publicToken ) => {
this.setState( { publicToken } );
};
render() {
const {
oauth2Client,
query,
translate,
showCheckYourEmail: showEmailLinkVerification,
isWooJPC,
isJetpackLogin,
isFromJetpackOnboarding,
} = this.props;
const { showSecondaryEmailOptions, showEmailCodeVerification, usernameOrEmail } = this.state;
if ( isGravPoweredOAuth2Client( oauth2Client ) ) {
let renderContent = this.renderGravPoweredMagicLogin();
const hasSubHeader =
isGravatarFlowOAuth2Client( oauth2Client ) ||
( isGravatarOAuth2Client( oauth2Client ) &&
( query?.gravatar_from === GRAVATAR_FROM_3RD_PARTY ||
query?.gravatar_from === GRAVATAR_FROM_QUICK_EDITOR ) );
if ( showSecondaryEmailOptions ) {
renderContent = this.renderGravPoweredSecondaryEmailOptions();
} else if ( showEmailCodeVerification ) {
renderContent = this.renderGravPoweredEmailCodeVerification();
} else if ( showEmailLinkVerification ) {
renderContent = this.renderGravPoweredEmailLinkVerification();
}
return (
{ renderContent }
);
}
// "query?.redirect_to" is used to determine if Studio app users are creating a new account (vs. logging in)
const isStudio = isStudioAppOAuth2Client( oauth2Client ) && query?.redirect_to;
// If this is part of the Jetpack login flow, some steps will display a different UI
const requestLoginEmailFormProps = {
...( this.props.isJetpackLogin ? { flow: 'jetpack' } : {} ),
isJetpackMagicLinkSignUpEnabled: this.props.isJetpackLogin,
createAccountForNewUser: true,
isFromJetpackOnboarding,
tosComponent: this.renderTos(),
...( isStudio
? {
customFormLabel: translate( 'Your email address' ),
submitButtonLabel: translate( 'Send activation link' ),
}
: {} ),
};
const mainContent = (
{ isWooJPC ? (
) : (
<>
{ shouldUseMagicCode( { isJetpack: isJetpackLogin } ) ? (
) : (
) }
>
) }
{ this.renderLinks() }
{ this.renderLocaleSuggestions() }
);
return (
{ mainContent }
);
}
}
const mapState = ( state ) => ( {
locale: getCurrentLocaleSlug( state ),
query: getCurrentQueryArguments( state ),
showCheckYourEmail: getMagicLoginCurrentView( state ) === CHECK_YOUR_EMAIL_PAGE,
isSendingEmail: isFetchingMagicLoginEmail( state ),
emailRequested: isMagicLoginEmailRequested( state ),
emailRequestError: getMagicLoginRequestEmailError( state ),
isJetpackLogin: getCurrentRoute( state )?.startsWith( '/log-in/jetpack/link' ),
oauth2Client: getCurrentOAuth2Client( state ),
userEmail:
getLastCheckedUsernameOrEmail( state ) ||
getCurrentQueryArguments( state ).email_address ||
getInitialQueryArguments( state ).email_address,
localeSuggestions: getLocaleSuggestions( state ),
isWCCOM: getIsWCCOM( state ),
isValidatingCode: isFetchingMagicLoginAuth( state ),
isCodeValidated: getMagicLoginRequestedAuthSuccessfully( state ),
codeValidationError: getMagicLoginRequestAuthError( state ),
twoFactorEnabled: isTwoFactorEnabled( state ),
twoFactorNotificationSent: getTwoFactorNotificationSent( state ),
redirectToSanitized: getRedirectToSanitized( state ),
redirectToOriginal: getRedirectToOriginal( state ),
isFromAutomatticForAgenciesPlugin:
'automattic-for-agencies-client' ===
new URLSearchParams( getRedirectToOriginal( state )?.split( '?' )[ 1 ] ).get( 'from' ),
isFromJetpackOnboarding:
new URLSearchParams( getRedirectToOriginal( state )?.split( '?' )[ 1 ] ).get( 'from' ) ===
'jetpack-onboarding',
isWooJPC: isWooJPCFlow( state ),
publicToken: getMagicLoginPublicToken( state ),
isFromAkismet: isAkismetRedirect(
new URLSearchParams( getRedirectToOriginal( state )?.split( '?' )[ 1 ] ).get( 'back' )
),
} );
const mapDispatch = {
hideMagicLoginRequestForm,
sendEmailLogin,
fetchMagicLoginAuthenticate,
rebootAfterLogin,
recordPageView: withEnhancers( recordPageView, [ enhanceWithSiteType ] ),
recordTracksEvent: withEnhancers( recordTracksEvent, [ enhanceWithSiteType ] ),
infoNotice,
errorNotice,
successNotice,
removeNotice,
};
export default connect( mapState, mapDispatch )( localize( MagicLogin ) );