File size: 1,950 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
import { Card } from '@automattic/components';
import debugFactory from 'debug';
import { localize } from 'i18n-calypso';
import PropTypes from 'prop-types';
import { Component } from 'react';
import { connect } from 'react-redux';
import { registerSecurityKey } from 'calypso/lib/webauthn';
import { errorNotice, warningNotice, successNotice } from 'calypso/state/notices/actions';
import Security2faKeyAddName from './name';
import WaitForKey from './wait-for-key';

const debug = debugFactory( 'calypso:me:security-2fa-key' );

class Security2faKeyAdd extends Component {
	static propTypes = {
		onRegister: PropTypes.func.isRequired,
		onCancel: PropTypes.func.isRequired,
		registerRequests: PropTypes.object.isRequired,
	};

	state = {
		securityKeyName: '',
	};

	registerKey = ( securityKeyName ) => {
		this.setState( { securityKeyName } );
		registerSecurityKey( securityKeyName )
			.then( ( data ) => {
				debug( 'registered key with data', data );
				this.keyRegistered();
			} )
			.catch( ( e ) => {
				this.handleError( e );
			} );
	};

	handleError = ( e ) => {
		if ( 'Canceled' === e.error ) {
			this.props.warningNotice( e.message, {
				showDismiss: true,
				isPersistent: true,
				duration: 5000,
			} );
		} else {
			this.props.errorNotice( e.message );
		}
		this.props.onCancel();
	};

	keyRegistered = () => {
		this.props.successNotice(
			this.props.translate( 'Security key has been successfully registered.' ),
			{
				showDismiss: true,
				isPersistent: true,
				duration: 5000,
			}
		);
		this.props.onRegister();
	};

	render() {
		return (
			<Card>
				{ ! this.state.securityKeyName && (
					<Security2faKeyAddName
						onNameSubmit={ this.registerKey }
						onCancel={ this.props.onCancel }
					/>
				) }
				{ this.state.securityKeyName && <WaitForKey /> }
			</Card>
		);
	}
}

export default connect( null, {
	errorNotice,
	warningNotice,
	successNotice,
} )( localize( Security2faKeyAdd ) );