-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtotp.js
More file actions
462 lines (405 loc) · 11.2 KB
/
totp.js
File metadata and controls
462 lines (405 loc) · 11.2 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { Button, Flex, Modal, Notice, Spinner } from '@wordpress/components';
import { Icon, cancelCircleFilled } from '@wordpress/icons';
import { RawHTML, useCallback, useContext, useEffect, useRef, useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import ScreenLink from './screen-link';
import AutoTabbingInput from './auto-tabbing-input';
import { refreshRecord } from '../utilities/common';
import { GlobalContext } from '../script';
import Success from './success';
export default function TOTP( { onSuccess } ) {
const {
user: { totpEnabled },
} = useContext( GlobalContext );
const [ success, setSuccess ] = useState( false );
const afterTimeout = useCallback( () => {
setSuccess( false );
onSuccess();
}, [ onSuccess ] );
if ( success ) {
return (
<Flex className="wporg-2fa__totp_success" direction="column">
<Success
message="Success! Your two-factor authentication app is set up."
afterTimeout={ afterTimeout }
/>
</Flex>
);
}
if ( totpEnabled ) {
return <Manage />;
}
return <Setup setSuccess={ setSuccess } />;
}
/**
* Setup the TOTP provider.
*
* @param props
* @param props.setSuccess
*/
function Setup( { setSuccess } ) {
const {
user: { userRecord },
} = useContext( GlobalContext );
const {
record: { id: userId },
} = userRecord;
const [ secretKey, setSecretKey ] = useState( '' );
const [ qrCodeUrl, setQrCodeUrl ] = useState( '' );
const [ error, setError ] = useState( '' );
const [ setupMethod, setSetupMethod ] = useState( 'qr-code' );
const [ inputs, setInputs ] = useState( Array( 6 ).fill( '' ) );
const [ statusWaiting, setStatusWaiting ] = useState( false );
// Fetch the data needed to setup TOTP.
useEffect( () => {
// useEffect callbacks can't be async directly, because that'd return the promise as a "cleanup" function.
const fetchSetupData = async () => {
const response = await apiFetch( {
path: '/wporg-two-factor/1.0/totp-setup?user_id=' + userId,
} );
setSecretKey( response.secret_key );
setQrCodeUrl( response.qr_code_url );
};
fetchSetupData();
}, [ userId ] );
// Enable TOTP when button clicked.
const handleEnable = useCallback(
async ( event ) => {
event.preventDefault();
const code = inputs.join( '' );
try {
setError( '' );
setStatusWaiting( true );
await apiFetch( {
path: '/two-factor/1.0/totp/',
method: 'POST',
data: {
user_id: userId,
key: secretKey,
code,
enable_provider: true,
},
} );
await refreshRecord( userRecord );
setSuccess( true );
} catch ( handleEnableError ) {
setError( handleEnableError.message );
} finally {
setStatusWaiting( false );
}
},
[ inputs, secretKey, userId, userRecord, setSuccess ]
);
return (
<div className="wporg-2fa__totp_setup-container">
<p className="wporg-2fa__screen-intro">
Two-factor authentication adds an extra layer of security to your account. Use a
phone app like{ ' ' }
<a
href="https://support.google.com/accounts/answer/1066447"
target="_blank"
rel="noreferrer"
>
Google Authenticator
</a>{ ' ' }
or{ ' ' }
<a
href="https://www.microsoft.com/ko-kr/security/mobile-authenticator-app"
target="_blank"
rel="noreferrer"
>
Microsoft Authenticator
</a>{ ' ' }
when logging in to WordPress.org.
</p>
{ 'qr-code' === setupMethod && (
<SetupMethodQRCode setSetupMethod={ setSetupMethod } qrCodeUrl={ qrCodeUrl } />
) }
{ 'manual' === setupMethod && (
<SetupMethodManual setSetupMethod={ setSetupMethod } secretKey={ secretKey } />
) }
<SetupForm
handleEnable={ handleEnable }
qrCodeUrl={ qrCodeUrl }
secretKey={ secretKey }
inputs={ inputs }
setInputs={ setInputs }
error={ error }
setError={ setError }
isBusy={ statusWaiting }
/>
</div>
);
}
/**
* Render the QR code methods for setting up TOTP in an app.
*
* @param props
* @param props.setSetupMethod
* @param props.qrCodeUrl
*/
function SetupMethodQRCode( { setSetupMethod, qrCodeUrl } ) {
const handleClick = useCallback( () => setSetupMethod( 'manual' ), [ setSetupMethod ] );
return (
<div className="wporg-2fa__totp_setup-method-container">
<p>
<strong>Scan the QR code with your authentication app </strong>
</p>
<Button variant="link" onClick={ handleClick }>
Can't scan the QR code?
</Button>
<div className="wporg-2fa__qr-code">
{ ! qrCodeUrl && 'Loading...' }
{ qrCodeUrl && (
<a href={ qrCodeUrl } aria-label="QR code to scan">
<RawHTML>{ createQrCode( qrCodeUrl ) }</RawHTML>
</a>
) }
</div>
</div>
);
}
/**
* Render the manual method for setting up TOTP in an app.
*
* @param props
* @param props.setSetupMethod
* @param props.secretKey
*/
function SetupMethodManual( { setSetupMethod, secretKey } ) {
const groups = ( secretKey || '' ).match( /.{1,4}/g );
const readableSecretKey = groups ? groups.join( ' ' ) : '';
const handleClick = useCallback( () => setSetupMethod( 'qr-code' ), [ setSetupMethod ] );
return (
<div className="wporg-2fa__manual">
<p>
<strong>Enter this time code into your app </strong>
</p>
<Button variant="link" onClick={ handleClick }>
Prefer to scan a QR code?
</Button>
<code>{ readableSecretKey }</code>
</div>
);
}
/*
* Generate a QR code SVG.
*
* @param {string} data The data to encode in the QR code.
*/
function createQrCode( data ) {
const { qrcode } = window; // Loaded via block.json.
/*
* 0 = Automatically select the version, to avoid going over the limit of URL
* length.
* L = Least amount of error correction, because it's not needed when scanning
* on a monitor, and it lowers the image size.
*/
const qr = qrcode( 0, 'L' );
qr.addData( data );
qr.make();
return qr.createSvgTag( 5 );
}
/**
* Render the form for entering the TOTP code.
*
* @param props
* @param props.handleEnable
* @param props.qrCodeUrl
* @param props.secretKey
* @param props.inputs
* @param props.setInputs
* @param props.error
* @param props.setError
* @param props.isBusy
*/
function SetupForm( {
handleEnable,
qrCodeUrl,
secretKey,
inputs,
setInputs,
error,
setError,
isBusy,
} ) {
const inputsRef = useRef( inputs );
useEffect( () => {
const prevInputs = inputsRef.current;
inputsRef.current = inputs;
// Clear the error if any of the inputs have changed
if ( error && inputs.some( ( input, index ) => input !== prevInputs[ index ] ) ) {
setError( '' );
}
}, [ error, inputs, setError ] );
const handleClearClick = useCallback( () => {
setInputs( Array( 6 ).fill( '' ) );
}, [ setInputs ] );
const canSubmit = qrCodeUrl && secretKey && inputs.every( ( input ) => !! input );
return (
<div className="wporg-2fa__setup-form-container">
{ error && (
<Notice status="error" isDismissible={ false } className="is-shown">
<Icon icon={ cancelCircleFilled } /> { error }
</Notice>
) }
<form className="wporg-2fa__setup-form" onSubmit={ handleEnable }>
<p>Enter the six digit code provided by the app:</p>
<AutoTabbingInput
inputs={ inputs }
setInputs={ setInputs }
error={ error }
setError={ setError }
/>
<div className="wporg-2fa__submit-actions">
<Button
type="submit"
variant="primary"
disabled={ ! canSubmit }
isBusy={ isBusy }
aria-label="Submit input digits"
>
{ isBusy ? 'Verifying' : 'Enable' }
</Button>
<Button
variant="secondary"
onClick={ handleClearClick }
aria-label="Clear all inputs"
>
Clear
</Button>
</div>
</form>
</div>
);
}
/**
* Disable the TOTP provider.
*/
function Manage() {
const {
user: { userRecord },
setGlobalNotice,
} = useContext( GlobalContext );
const [ error, setError ] = useState( '' );
const [ disabling, setDisabling ] = useState( false );
const [ confirmingDisable, setConfirmingDisable ] = useState( false );
/**
* Display the confirmation modal for disabling the TOTP provider.
*/
const showConfirmDisableModal = useCallback( () => {
setConfirmingDisable( true );
}, [] );
/**
* Remove the confirmation modal for disabling the TOTP provider.
*/
const hideConfirmDisableModal = useCallback( () => {
setConfirmingDisable( false );
}, [] );
// Disable TOTP when button clicked.
const handleDisable = useCallback(
async ( event ) => {
event.preventDefault();
setError( '' );
setDisabling( true );
try {
await apiFetch( {
path: '/two-factor/1.0/totp/',
method: 'DELETE',
data: { user_id: userRecord.record.id },
} );
await refreshRecord( userRecord );
setGlobalNotice( 'Successfully disabled your two-factor app.' );
} catch ( handleDisableError ) {
hideConfirmDisableModal();
setError( handleDisableError.message );
} finally {
setDisabling( false );
}
},
[ hideConfirmDisableModal, setGlobalNotice, userRecord ]
);
return (
<>
<div className="wporg-2fa__screen-intro">
<p>
You've enabled two-factor authentication on your account — smart move! When
you log in to WordPress.org, you'll need to enter your username and
password, and then enter a unique passcode generated by an app on your mobile
device.
</p>
<p>
Make sure you've created{ ' ' }
<ScreenLink screen="backup-codes" anchorText="backup codes" /> and saved them in
a safe location, in case you ever lose your device. You may also need them when
transitioning to a new device. Without them you may permanently lose access to
your account.
</p>
<p>
<strong>Status:</strong> Two-Factor app is currently{ ' ' }
<span className="wporg-2fa__enabled-status">on</span>.
</p>
</div>
<p className="wporg-2fa__submit-actions">
<Button variant="secondary" onClick={ showConfirmDisableModal }>
Disable Two-Factor app
</Button>
</p>
{ error && (
<Notice status="error" isDismissible={ false }>
<Icon icon={ cancelCircleFilled } />
{ error }
</Notice>
) }
{ confirmingDisable && (
<ConfirmDisableApp
error={ error }
disabling={ disabling }
onClose={ hideConfirmDisableModal }
onConfirm={ handleDisable }
/>
) }
</>
);
}
/**
* Prompt the user to confirm they want to disable their two-factor app.
*
* @param {Object} props
* @param {Function} props.onConfirm
* @param {Function} props.onClose
* @param {boolean} props.disabling
*/
function ConfirmDisableApp( { onConfirm, onClose, disabling } ) {
return (
<Modal
title={ `Disable Two-Factor app` }
className="wporg-2fa__confirm-disable-app"
onRequestClose={ onClose }
>
<p className="wporg-2fa__screen-intro">
Are you sure you want to disable your two-factor app?
</p>
{ disabling ? (
<div className="wporg-2fa__process-status">
<Spinner />
</div>
) : (
<div className="wporg-2fa__submit-actions">
<Button variant="primary" isDestructive onClick={ onConfirm }>
Disable Two-Factor app
</Button>
<Button variant="tertiary" onClick={ onClose }>
Cancel
</Button>
</div>
) }
</Modal>
);
}