File size: 9,204 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
/* eslint-disable no-nested-ternary */
import { PLAN_BUSINESS, PLAN_ECOMMERCE, getPlan } from '@automattic/calypso-products';
import { Button, CompactCard, Dialog, LoadingPlaceholder } from '@automattic/components';
import { localizeUrl } from '@automattic/i18n-utils';
import styled from '@emotion/styled';
import { createInterpolateElement } from '@wordpress/element';
import { sprintf } from '@wordpress/i18n';
import { useI18n } from '@wordpress/react-i18n';
import { useState } from 'react';
import DocumentHead from 'calypso/components/data/document-head';
import HeaderCake from 'calypso/components/header-cake';
import InlineSupportLink from 'calypso/components/inline-support-link';
import Main from 'calypso/components/main';
import NavigationHeader from 'calypso/components/navigation-header';
import PageViewTracker from 'calypso/lib/analytics/page-view-tracker';
import twoStepAuthorization from 'calypso/lib/two-step-authorization';
import ReauthRequired from 'calypso/me/reauth-required';
import { useDispatch, useSelector } from 'calypso/state';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { getCurrentUser } from 'calypso/state/current-user/selectors';
import { errorNotice, removeNotice, successNotice } from 'calypso/state/notices/actions';
import { AddSSHKeyForm } from './add-ssh-key-form';
import { ManageSSHKeys } from './manage-ssh-keys';
import { UpdateSSHKeyForm } from './update-ssh-key-form';
import { useAddSSHKeyMutation } from './use-add-ssh-key-mutation';
import { useDeleteSSHKeyMutation } from './use-delete-ssh-key-mutation';
import { useSSHKeyQuery } from './use-ssh-key-query';
import { useUpdateSSHKeyMutation } from './use-update-ssh-key-mutation';

const SSHKeyLoadingPlaceholder = styled( LoadingPlaceholder )< { width?: string } >`
	:not( :last-child ) {
		margin-block-end: 0.5rem;
	}
	width: ${ ( props ) => ( props.width ? props.width : '100%' ) };
`;
interface SecuritySSHKeyQueryParams {
	siteSlug?: string;
	source?: string;
}
interface SecuritySSHKeyProps {
	queryParams: SecuritySSHKeyQueryParams;
}

const Placeholders = () => (
	<CompactCard>
		<SSHKeyLoadingPlaceholder width="18%" />
		<SSHKeyLoadingPlaceholder width="45%" />
		<SSHKeyLoadingPlaceholder width="25%" />
	</CompactCard>
);

const noticeOptions = {
	duration: 3000,
};

const sshKeySaveFailureNoticeId = 'ssh-key-save-failure';
const sshKeyUpdateFailureNoticeId = 'ssh-key-update-failure';

const UpdateSSHModalTitle = styled.h1( {
	margin: '0 0 16px',
} );

const UpdateSSHModalDescription = styled.div( {
	margin: '0 0 16px',
} );

const CancelDialogButton = styled( Button )( {
	marginInlineStart: '10px',
} );

const UpdateSSHDialogContainer = styled.div( {
	width: '900px',
	maxWidth: '100%',
} );

export const SecuritySSHKey = ( { queryParams }: SecuritySSHKeyProps ) => {
	const { data, isLoading } = useSSHKeyQuery();
	const dispatch = useDispatch();
	const currentUser = useSelector( getCurrentUser );
	const [ sshKeyNameToUpdate, setSSHKeyNameToUpdate ] = useState( '' );
	const [ oldSSHFingerprint, setOldSSHFingerprint ] = useState( '' );
	const [ showDialog, setShowDialog ] = useState( false );
	const { __ } = useI18n();

	const { addSSHKey, isPending: isAdding } = useAddSSHKeyMutation( {
		onMutate: () => {
			dispatch( removeNotice( sshKeySaveFailureNoticeId ) );
		},
		onSuccess: () => {
			dispatch( recordTracksEvent( 'calypso_security_ssh_key_add_success' ) );
			dispatch( successNotice( __( 'SSH key added to account.' ), noticeOptions ) );
		},
		onError: ( error ) => {
			dispatch(
				recordTracksEvent( 'calypso_security_ssh_key_add_failure', {
					code: error.code,
				} )
			);
			dispatch(
				errorNotice(
					// translators: "reason" is why adding the ssh key failed.
					sprintf( __( 'Failed to save SSH key: %(reason)s' ), { reason: error.message } ),
					{
						...noticeOptions,
						id: sshKeySaveFailureNoticeId,
					}
				)
			);
		},
	} );

	const { deleteSSHKey, keyBeingDeleted } = useDeleteSSHKeyMutation( {
		onSuccess: () => {
			dispatch( recordTracksEvent( 'calypso_security_ssh_key_delete_success' ) );
			dispatch( successNotice( __( 'SSH key removed from account.' ), noticeOptions ) );
		},
		onError: ( error ) => {
			dispatch(
				recordTracksEvent( 'calypso_security_ssh_key_delete_failure', {
					code: error.code,
				} )
			);
			dispatch(
				errorNotice(
					// translators: "reason" is why deleting the ssh key failed.
					sprintf( __( 'Failed to delete SSH key: %(reason)s' ), { reason: error.message } ),
					noticeOptions
				)
			);
		},
	} );

	const { updateSSHKey, isPending: keyBeingUpdated } = useUpdateSSHKeyMutation( {
		onMutate: () => {
			dispatch( removeNotice( sshKeyUpdateFailureNoticeId ) );
		},
		onSuccess: () => {
			dispatch( recordTracksEvent( 'calypso_security_ssh_key_update_success' ) );
			dispatch( successNotice( __( 'SSH key updated for account.' ), noticeOptions ) );
			setSSHKeyNameToUpdate( '' );
			setOldSSHFingerprint( '' );
			setShowDialog( false );
		},
		onError: ( error ) => {
			dispatch(
				recordTracksEvent( 'calypso_security_ssh_key_update_failure', {
					code: error.code,
				} )
			);
			dispatch(
				errorNotice(
					// translators: "reason" is why adding the ssh key failed.
					sprintf( __( 'Failed to update SSH key: %(reason)s' ), { reason: error.message } ),
					{
						...noticeOptions,
						id: sshKeyUpdateFailureNoticeId,
					}
				)
			);
		},
	} );

	const hasKeys = data && data.length > 0;
	const redirectToHosting =
		queryParams.source && queryParams.source === 'hosting-config' && queryParams.siteSlug;
	const redirectToSettings =
		queryParams.source && queryParams.source === 'sites/settings/sftp-ssh' && queryParams.siteSlug;

	const closeDialog = () => setShowDialog( false );

	return (
		<Main wideLayout className="security">
			<PageViewTracker path="/me/security/ssh-key" title="Me > SSH Key" />
			<ReauthRequired twoStepAuthorization={ twoStepAuthorization } />

			<NavigationHeader navigationItems={ [] } title={ __( 'Security' ) } />

			<HeaderCake
				backText={ __( 'Back' ) }
				backHref={
					redirectToHosting || redirectToSettings
						? `/${ queryParams.source }/${ queryParams.siteSlug }`
						: '/me/security'
				}
			>
				{ __( 'SSH Key' ) }
			</HeaderCake>

			<DocumentHead title={ __( 'SSH Key' ) } />

			<CompactCard>
				<div>
					<p>
						{ __(
							'Add a SSH key to your WordPress.com account to make it available for SFTP and SSH authentication.'
						) }
					</p>
					<p>
						{ sprintf(
							// translators: %1$s is the short-form name of the Business plan, %2$s is the short-form name of the eCommerce plan.
							__(
								'Once added, attach the SSH key to a site with a %1$s or %2$s plan to enable SSH key authentication for that site.'
							),
							getPlan( PLAN_BUSINESS )?.getTitle() || '',
							getPlan( PLAN_ECOMMERCE )?.getTitle() || ''
						) }
					</p>
					<p style={ isLoading || hasKeys ? { marginBlockEnd: 0 } : undefined }>
						{ createInterpolateElement(
							__(
								'If the SSH key is removed from your WordPress.com account, it will also be removed from all attached sites. <a>Read more.</a>'
							),
							{
								br: <br />,
								a: (
									<InlineSupportLink
										supportPostId={ 100385 }
										supportLink={ localizeUrl(
											'https://developer.wordpress.com/docs/developer-tools/ssh/'
										) }
										showIcon={ false }
									/>
								),
							}
						) }
					</p>
				</div>

				{ currentUser?.username && (
					<Dialog isVisible={ showDialog } onClose={ closeDialog } showCloseIcon shouldCloseOnEsc>
						<UpdateSSHDialogContainer>
							<UpdateSSHModalTitle>{ __( 'Update SSH Key' ) }</UpdateSSHModalTitle>
							<UpdateSSHModalDescription>
								<p>
									{ __(
										'Replace your current SSH key with a new SSH key to use the new SSH key with all attached sites.'
									) }
								</p>
							</UpdateSSHModalDescription>
							<UpdateSSHKeyForm
								userLogin={ currentUser.username }
								oldSSHFingerprint={ oldSSHFingerprint }
								keyName={ sshKeyNameToUpdate }
								updateSSHKey={ updateSSHKey }
								isUpdating={ keyBeingUpdated }
								updateText={ __( 'Update SSH Key' ) }
							>
								<CancelDialogButton disabled={ keyBeingUpdated } onClick={ closeDialog }>
									Cancel
								</CancelDialogButton>
							</UpdateSSHKeyForm>
						</UpdateSSHDialogContainer>
					</Dialog>
				) }
				{ ! isLoading && ! hasKeys ? (
					<AddSSHKeyForm
						addSSHKey={ ( { name, key } ) => addSSHKey( { name, key } ) }
						isAdding={ isAdding }
					/>
				) : null }
			</CompactCard>
			{ isLoading && <Placeholders /> }
			{ hasKeys && currentUser?.username && (
				<ManageSSHKeys
					userLogin={ currentUser.username }
					sshKeys={ data }
					onDelete={ ( sshKeyName ) => deleteSSHKey( { sshKeyName } ) }
					onUpdate={ ( sshKeyName, keyFingerprint ) => {
						setSSHKeyNameToUpdate( sshKeyName );
						setOldSSHFingerprint( keyFingerprint );
						setShowDialog( true );
					} }
					keyBeingUpdated={ keyBeingUpdated }
					keyBeingDeleted={ keyBeingDeleted }
				/>
			) }
		</Main>
	);
};