File size: 10,198 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { Button, Card, Dialog, FormInputValidation, FormLabel } from '@automattic/components';
import { supported } from '@github/webauthn-json';
import debugFactory from 'debug';
import { localize } from 'i18n-calypso';
import PropTypes from 'prop-types';
import { Component } from 'react';
import { connect } from 'react-redux';
import CardHeading from 'calypso/components/card-heading';
import FormButton from 'calypso/components/forms/form-button';
import FormCheckbox from 'calypso/components/forms/form-checkbox';
import FormFieldset from 'calypso/components/forms/form-fieldset';
import FormVerificationCodeInput from 'calypso/components/forms/form-verification-code-input';
import Notice from 'calypso/components/notice';
import WarningCard from 'calypso/components/warning-card';
import { recordGoogleEvent } from 'calypso/state/analytics/actions';
import { redirectToLogout } from 'calypso/state/current-user/actions';
import SecurityKeyForm from './security-key-form';
import TwoFactorActions from './two-factor-actions';
import './style.scss';

const debug = debugFactory( 'calypso:me:reauth-required' );

// autofocus is used for tracking purposes, not an a11y issue
/* eslint-disable jsx-a11y/no-autofocus, jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions, jsx-a11y/anchor-is-valid */
class ReauthRequired extends Component {
	codeRequestTimer = false;

	constructor( props ) {
		super( props );

		this.state = {
			remember2fa: false, // Should the 2fa be remembered for 30 days?
			code: '', // User's generated 2fa code
			smsRequestsAllowed: true, // Can the user request another SMS code?
			twoFactorAuthType: 'authenticator',
		};
	}

	componentDidMount() {
		this.props.twoStepAuthorization.on( 'change', this.update );
	}

	componentWillUnmount() {
		clearTimeout( this.codeRequestTimer );
		this.props.twoStepAuthorization.off( 'change', this.update );
	}

	update = () => {
		this.forceUpdate();
	};

	getClickHandler = ( action, callback ) => () => {
		this.props.recordGoogleEvent( 'Me', 'Clicked on ' + action );

		if ( callback ) {
			callback();
		}
	};

	getCheckboxHandler = ( checkboxName ) => ( event ) => {
		const action = 'Clicked ' + checkboxName + ' checkbox';
		const value = event.target.checked ? 1 : 0;

		this.props.recordGoogleEvent( 'Me', action, 'checked', value );
	};

	getFocusHandler = ( action ) => () =>
		this.props.recordGoogleEvent( 'Me', 'Focused on ' + action );

	renderCodeMessage() {
		if ( this.props.twoStepAuthorization.isTwoStepSMSEnabled() ) {
			return this.props.translate(
				'Press the button below to request an SMS verification code. ' +
					'Once you receive our text message at your phone number ending with ' +
					'{{strong}}%(smsLastFour)s{{/strong}} , enter the code below.',
				{
					args: {
						smsLastFour: this.props.twoStepAuthorization.getSMSLastFour(),
					},
					components: {
						strong: <strong />,
					},
				}
			);
		}
		if ( this.state.twoFactorAuthType === 'sms' ) {
			return this.props.translate(
				'We just sent you a verification code to your phone number on file, please enter the code below.'
			);
		}

		return this.props.translate(
			'Please enter the verification code generated by your authenticator app.'
		);
	}

	submitForm = ( event ) => {
		event.preventDefault();
		this.setState( { validatingCode: true } );

		this.props.twoStepAuthorization.validateCode(
			{
				code: this.state.code,
				remember2fa: this.state.remember2fa,
			},
			( error, data ) => {
				this.setState( { validatingCode: false } );
				if ( error ) {
					debug( 'There was an error validating that code: ' + JSON.stringify( error ) );
				} else {
					debug( 'The code validated!' + JSON.stringify( data ) );
				}
			}
		);
	};

	sendSMSCode() {
		this.setState( { smsRequestsAllowed: false } );
		this.codeRequestTimer = setTimeout( () => {
			this.setState( { smsRequestsAllowed: true } );
		}, 60000 );

		this.props.twoStepAuthorization.sendSMSCode( ( error, data ) => {
			if ( ! error && data.sent ) {
				debug( 'SMS code successfully sent' );
			} else {
				debug( 'There was a failure sending the SMS code.' );
			}
		} );
	}

	preValidateAuthCode() {
		return this.state.code.length && this.state.code.length > 5;
	}

	renderFailedValidationMsg() {
		if ( ! this.props.twoStepAuthorization.codeValidationFailed() ) {
			return null;
		}

		return (
			<FormInputValidation
				isError
				text={ this.props.translate( 'You entered an invalid code. Please try again.' ) }
			/>
		);
	}

	renderSMSResendThrottled() {
		if ( ! this.props.twoStepAuthorization.isSMSResendThrottled() ) {
			return null;
		}

		return (
			<div className="reauth-required__send-sms-throttled">
				<Notice
					showDismiss={ false }
					text={ this.props.translate(
						'SMS codes are limited to once per minute. Please wait and try again.'
					) }
				/>
			</div>
		);
	}

	renderVerificationForm() {
		const enhancedSecurity = this.props.twoStepAuthorization.data?.two_step_enhanced_security;
		if ( enhancedSecurity ) {
			return this.renderSecurityKeyUnsupported();
		}
		const method = this.props.twoStepAuthorization.isTwoStepSMSEnabled() ? 'sms' : 'app';
		return (
			<Card compact>
				<p>{ this.renderCodeMessage() }</p>

				<p>
					<a
						className="reauth-required__sign-out"
						onClick={ this.getClickHandler(
							'Reauth Required Log Out Link',
							this.props.redirectToLogout
						) }
					>
						{ this.props.translate( 'Not you? Log out' ) }
					</a>
				</p>

				<form onSubmit={ this.submitForm }>
					<FormFieldset>
						<FormLabel htmlFor="code">{ this.props.translate( 'Verification Code' ) }</FormLabel>
						<FormVerificationCodeInput
							autoFocus
							id="code"
							isError={ this.props.twoStepAuthorization.codeValidationFailed() }
							name="code"
							method={ method }
							onFocus={ this.getFocusHandler( 'Reauth Required Verification Code Field' ) }
							value={ this.state.code }
							onChange={ this.handleChange }
						/>

						{ this.renderFailedValidationMsg() }
					</FormFieldset>

					<FormFieldset>
						<FormLabel>
							<FormCheckbox
								id="remember2fa"
								name="remember2fa"
								onClick={ this.getCheckboxHandler( 'Remember 2fa' ) }
								checked={ this.state.remember2fa }
								onChange={ this.handleCheckedChange }
							/>
							<span>{ this.props.translate( 'Remember for 30 days.' ) }</span>
						</FormLabel>
					</FormFieldset>

					{ this.renderSMSResendThrottled() }

					<FormButton
						className="reauth-required__button"
						disabled={ this.state.validatingCode || ! this.preValidateAuthCode() }
						onClick={ this.getClickHandler( 'Submit Validation Code on Reauth Required' ) }
					>
						{ this.props.translate( 'Verify' ) }
					</FormButton>
				</form>
			</Card>
		);
	}

	renderSecurityKeyUnsupported() {
		const { translate } = this.props;

		return (
			<Card compact>
				<CardHeading tagName="h2">
					{ translate( 'Two Factor Authentication Required' ) }
				</CardHeading>
				<WarningCard
					message={ translate(
						'Your WordPress.com account requires the use of security keys, but the current device does not seem to support them.'
					) }
				/>
				<Button
					onClick={ this.getClickHandler(
						'Reauth Required Log Out Link',
						this.props.redirectToLogout
					) }
					primary
					className="reauth-required__button reauth-required__logout"
				>
					{ translate( 'Log out' ) }
				</Button>
			</Card>
		);
	}

	renderDialog() {
		const enhancedSecurity = this.props.twoStepAuthorization.data?.two_step_enhanced_security;
		const method = this.props.twoStepAuthorization.isTwoStepSMSEnabled() ? 'sms' : 'authenticator';
		const isSecurityKeySupported =
			this.props.twoStepAuthorization.isSecurityKeyEnabled() && supported();
		const twoFactorAuthType = enhancedSecurity ? 'webauthn' : this.state.twoFactorAuthType;
		// This enables the SMS button on the security key form regardless if we can send SMS or not.
		// Otherwise, there's no way to go back to the verification form if smsRequestsAllowed is false.
		const shouldEnableSmsButton =
			this.state.smsRequestsAllowed || ( method === 'sms' && twoFactorAuthType === 'webauthn' );

		const hasSmsRecoveryNumber =
			!! this.props?.twoStepAuthorization?.data?.two_step_sms_last_four?.length;

		return (
			<Dialog
				bodyOpenClassName="ReactModal__Body--open reauth-required__dialog-body"
				autoFocus={ false }
				className="reauth-required__dialog"
				isVisible={ this.props?.twoStepAuthorization.isReauthRequired() }
			>
				{ isSecurityKeySupported && twoFactorAuthType === 'webauthn' ? (
					<SecurityKeyForm twoStepAuthorization={ this.props.twoStepAuthorization } />
				) : (
					this.renderVerificationForm()
				) }
				<TwoFactorActions
					twoFactorAuthType={ twoFactorAuthType }
					onChange={ this.handleAuthSwitch }
					isSmsSupported={
						! enhancedSecurity &&
						( method === 'sms' || ( method === 'authenticator' && hasSmsRecoveryNumber ) )
					}
					isAuthenticatorSupported={ ! enhancedSecurity && method !== 'sms' }
					isSmsAllowed={ shouldEnableSmsButton }
					isSecurityKeySupported={ isSecurityKeySupported }
				/>
			</Dialog>
		);
	}

	render() {
		return (
			<>
				{ this.renderDialog() }
				{ this.props.twoStepAuthorization.initialized &&
					! this.props.twoStepAuthorization.isReauthRequired() &&
					this.props.children?.() }
			</>
		);
	}

	handleAuthSwitch = ( authType ) => {
		this.setState( { twoFactorAuthType: authType } );
		if ( authType === 'sms' ) {
			this.sendSMSCode();
		}
	};

	handleChange = ( e ) => {
		const { name, value } = e.currentTarget;
		this.setState( { [ name ]: value } );
	};

	handleCheckedChange = ( e ) => {
		const { name, checked } = e.currentTarget;
		this.setState( { [ name ]: checked } );
	};
}

ReauthRequired.propTypes = {
	twoStepAuthorization: PropTypes.object.isRequired,
};

/* eslint-enable jsx-a11y/no-autofocus, jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions, jsx-a11y/anchor-is-valid */

export default connect( null, {
	redirectToLogout,
	recordGoogleEvent,
} )( localize( ReauthRequired ) );