-
Notifications
You must be signed in to change notification settings - Fork 565
/
Copy pathdefaultCredentialSelectionDataProvider.ts
317 lines (275 loc) · 12.5 KB
/
defaultCredentialSelectionDataProvider.ts
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
/*!
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// Implements a multi-step capable selector for traditional AWS credential profiles
// (access key/secret key based) for with the ability for users to add new credential
// profiles. As other sign-in mechanisms become available in the future, we should be
// able to extend this selector to handle them quite easily. The handler currently
// returns the name of the selected or created credential profile.
//
// Based on the multiStepInput code in the QuickInput VSCode extension sample.
import * as vscode from 'vscode'
import * as semver from 'semver'
import * as nls from 'vscode-nls'
const localize = nls.loadMessageBundle()
import { asString } from '../../credentials/providers/credentials'
import { SharedCredentialsProvider } from '../../credentials/providers/sharedCredentialsProvider'
import { MultiStepInputFlowController } from '../multiStepInputFlowController'
import { CredentialSelectionDataProvider } from './credentialSelectionDataProvider'
import { CredentialSelectionState } from './credentialSelectionState'
import { CredentialsProfileMru } from './credentialsProfileMru'
import { getIdeProperties } from '../extensionUtilities'
import { credentialHelpUrl } from '../constants'
import { createHelpButton } from '../ui/buttons'
import { recentlyUsed } from '../localizedText'
import { messages } from '../utilities/messages'
interface ProfileEntry {
profileName: string
isRecentlyUsed: boolean
}
export class DefaultCredentialSelectionDataProvider implements CredentialSelectionDataProvider {
private static readonly defaultCredentialsProfileName = asString({
credentialSource: SharedCredentialsProvider.getProviderType(),
credentialTypeId: 'default',
})
private readonly _credentialsMru: CredentialsProfileMru
private readonly helpButton = createHelpButton(credentialHelpUrl)
public constructor(public readonly existingProfileNames: string[], protected context: vscode.ExtensionContext) {
this._credentialsMru = new CredentialsProfileMru(context)
}
public async pickCredentialProfile(
input: MultiStepInputFlowController,
actions: vscode.QuickPickItem[],
state: Partial<CredentialSelectionState>
): Promise<vscode.QuickPickItem> {
// Remove this stub after we bump minimum to vscode 1.64
const QuickPickItemKind = semver.gte(vscode.version, '1.64.0') ? (vscode as any).QuickPickItemKind : undefined
const menuTop: vscode.QuickPickItem[] = [
// vscode 1.64 supports QuickPickItemKind.Separator.
// https://github.com/microsoft/vscode/commit/eb416b4f9ebfda1c798aa7c8b2f4e81c6ce1984f
...(!QuickPickItemKind
? []
: [
{
label: localize('AWS.menu.actions', 'Actions'),
kind: QuickPickItemKind.Separator,
} as vscode.QuickPickItem,
]),
...actions,
...(!QuickPickItemKind
? []
: [
{
label: localize('AWS.menu.profiles', 'Profiles'),
kind: QuickPickItemKind.Separator,
} as vscode.QuickPickItem,
]),
]
return await input.showQuickPick({
title: localize(
'AWS.title.selectCredentialProfile',
'Select an {0} credential profile',
getIdeProperties().company
),
step: 1,
totalSteps: 1,
placeholder: localize('AWS.placeHolder.selectProfile', 'Select a credential profile'),
items: menuTop.concat(this.getProfileSelectionList()),
activeItem: state.credentialProfile,
shouldResume: this.shouldResume.bind(this),
})
}
public async inputProfileName(
input: MultiStepInputFlowController,
state: Partial<CredentialSelectionState>
): Promise<string | undefined> {
const result = await input.showInputBox({
title: localize(
'AWS.title.createCredentialProfile',
'Create a new {0} credential profile',
getIdeProperties().company
),
step: 1,
totalSteps: 3,
value: '',
prompt: localize('AWS.placeHolder.newProfileName', 'Choose a unique name for the new profile'),
validate: this.validateProfileName.bind(this),
ignoreFocusOut: true,
shouldResume: this.shouldResume.bind(this),
buttons: [this.helpButton],
})
return typeof result === 'string' ? result : undefined
}
public async inputAccessKey(
input: MultiStepInputFlowController,
state: Partial<CredentialSelectionState>
): Promise<string | undefined> {
const result = await input.showInputBox({
title: localize(
'AWS.title.createCredentialProfile',
'Create a new {0} credential profile',
getIdeProperties().company
),
step: 2,
totalSteps: 3,
value: '',
prompt: localize('AWS.placeHolder.inputAccessKey', 'Input the {0} Access Key', getIdeProperties().company),
validate: this.validateAccessKey.bind(this),
ignoreFocusOut: true,
shouldResume: this.shouldResume.bind(this),
buttons: [this.helpButton],
})
return typeof result === 'string' ? result : undefined
}
public async inputSecretKey(
input: MultiStepInputFlowController,
state: Partial<CredentialSelectionState>
): Promise<string | undefined> {
const result = await input.showInputBox({
title: localize(
'AWS.title.createCredentialProfile',
'Create a new {0} credential profile',
getIdeProperties().company
),
step: 3,
totalSteps: 3,
value: '',
prompt: localize('AWS.placeHolder.inputSecretKey', 'Input the {0} Secret Key', getIdeProperties().company),
validate: this.validateSecretKey.bind(this),
ignoreFocusOut: true,
shouldResume: this.shouldResume.bind(this),
buttons: [this.helpButton],
})
return typeof result === 'string' ? result : undefined
}
public async validateProfileName(name: string): Promise<string | undefined> {
if (name === '') {
return localize('AWS.credentials.error.emptyProfileName', 'Profile name must not be empty')
}
const duplicate = this.existingProfileNames.find(k => k === name)
return duplicate ? 'Name not unique' : undefined
}
public async validateAccessKey(accessKey: string): Promise<string | undefined> {
// TODO: is there a regex pattern we could use?
if (accessKey === '') {
return localize('AWS.credentials.error.emptyAccessKey', 'Access key must not be empty')
}
return undefined
}
public async validateSecretKey(secretKey: string): Promise<string | undefined> {
// TODO: is there a regex pattern we could use?
if (secretKey === '') {
return localize('AWS.credentials.error.emptySecretKey', 'Secret key must not be empty')
}
return undefined
}
public async shouldResume(): Promise<boolean> {
// Could show a notification with the option to resume.
return false
}
/**
* Builds and returns the list of QuickPickItem objects representing the profile names to select from in the UI
*/
private getProfileSelectionList(): vscode.QuickPickItem[] {
const orderedProfiles: ProfileEntry[] = this.getOrderedProfiles()
const selectionList: vscode.QuickPickItem[] = []
orderedProfiles.forEach(profile => {
const selectionItem: vscode.QuickPickItem = { label: profile.profileName }
if (profile.isRecentlyUsed) {
selectionItem.description = recentlyUsed
}
selectionList.push(selectionItem)
})
return selectionList
}
/**
* Returns a list of profiles, and whether or not they have been
* used recently. Ordered by: MRU, default, all others
*/
private getOrderedProfiles(): ProfileEntry[] {
const mostRecentProfileNames = this.getMostRecentlyUsedProfileNames()
const orderedProfiles: ProfileEntry[] = []
const orderedNames = new Set()
// Add MRU entries first
mostRecentProfileNames.forEach(profileName => {
orderedProfiles.push({ profileName: profileName, isRecentlyUsed: true })
orderedNames.add(profileName)
})
// Add default if it hasn't been, and is an existing profile name
const defaultProfileName = DefaultCredentialSelectionDataProvider.defaultCredentialsProfileName
if (!orderedNames.has(defaultProfileName) && this.existingProfileNames.includes(defaultProfileName)) {
orderedProfiles.push({ profileName: defaultProfileName, isRecentlyUsed: false })
orderedNames.add(DefaultCredentialSelectionDataProvider.defaultCredentialsProfileName)
}
// Add remaining items, sorted alphanumerically
const remainingProfiles: ProfileEntry[] = this.existingProfileNames
.filter(x => !orderedNames.has(x))
.sort()
.map(profileName => ({ profileName: profileName, isRecentlyUsed: false }))
orderedProfiles.push(...remainingProfiles)
return orderedProfiles
}
/**
* Returns a list of the profile names that are currently in the MRU list
*/
private getMostRecentlyUsedProfileNames(): string[] {
const mru = this._credentialsMru.getMruList()
return mru.filter(x => this.existingProfileNames.includes(x))
}
}
export async function credentialProfileSelector(
dataProvider: CredentialSelectionDataProvider
): Promise<CredentialSelectionState | undefined> {
async function pickCredentialProfile(
input: MultiStepInputFlowController,
state: Partial<CredentialSelectionState>
) {
const actions = [
{
label: messages.editCredentials(true),
alwaysShow: true,
description: localize('AWS.credentials.edit.desc', 'open ~/.aws/credentials'),
},
]
const item = await dataProvider.pickCredentialProfile(input, actions, state)
if (item.label === actions[0].label) {
vscode.commands.executeCommand('aws.credentials.edit')
} else {
state.credentialProfile = item
}
}
async function collectInputs() {
const state: Partial<CredentialSelectionState> = {}
await MultiStepInputFlowController.run(async input => await pickCredentialProfile(input, state))
return state as CredentialSelectionState
}
return await collectInputs()
}
export async function promptToDefineCredentialsProfile(
dataProvider: CredentialSelectionDataProvider
): Promise<CredentialSelectionState> {
async function inputProfileName(input: MultiStepInputFlowController, state: Partial<CredentialSelectionState>) {
state.profileName = await dataProvider.inputProfileName(input, state)
/* tslint:disable promise-function-async */
return (inputController: MultiStepInputFlowController) => inputAccessKey(inputController, state)
/* tslint:enable promise-function-async */
}
async function inputAccessKey(input: MultiStepInputFlowController, state: Partial<CredentialSelectionState>) {
state.accesskey = await dataProvider.inputAccessKey(input, state)
/* tslint:disable promise-function-async */
return (inputController: MultiStepInputFlowController) => inputSecretKey(inputController, state)
/* tslint:enable promise-function-async */
}
async function inputSecretKey(input: MultiStepInputFlowController, state: Partial<CredentialSelectionState>) {
state.secretKey = await dataProvider.inputSecretKey(input, state)
}
async function collectInputs(): Promise<CredentialSelectionState> {
const state: Partial<CredentialSelectionState> = {}
/* tslint:disable promise-function-async */
await MultiStepInputFlowController.run(input => inputProfileName(input, state))
/* tslint:enable promise-function-async */
return state as CredentialSelectionState
}
return await collectInputs()
}