forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcredentials.ts
More file actions
227 lines (191 loc) · 7.32 KB
/
Copy pathcredentials.ts
File metadata and controls
227 lines (191 loc) · 7.32 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Octokit from '@octokit/rest';
import * as vscode from 'vscode';
import { IHostConfiguration, HostHelper } from '../authentication/configuration';
import { GitHubServer } from '../authentication/githubServer';
import { Remote } from '../common/remote';
import { VSCodeConfiguration } from '../authentication/vsConfiguration';
import Logger from '../common/logger';
import { ITelemetry } from './interface';
import { handler as uriHandler } from '../common/uri';
const TRY_AGAIN = 'Try again?';
const SIGNIN_COMMAND = 'Sign in';
const AUTH_INPUT_TOKEN_CMD = 'auth.inputTokenCallback';
export class CredentialStore {
private _octokits: Map<string, Octokit>;
private _configuration: VSCodeConfiguration;
private _authenticationStatusBarItems: Map<string, vscode.StatusBarItem>;
constructor(configuration: any,
private readonly _telemetry: ITelemetry) {
this._configuration = configuration;
this._octokits = new Map<string, Octokit>();
this._authenticationStatusBarItems = new Map<string, vscode.StatusBarItem>();
vscode.commands.registerCommand(AUTH_INPUT_TOKEN_CMD, async () => {
const uriStr = await vscode.window.showInputBox({ prompt: 'Token' });
if (!uriStr) { return; }
const uri = vscode.Uri.parse(uriStr);
if (!uri.scheme) {
return vscode.window.showErrorMessage('Invalid token');
}
uriHandler.handleUri(uri);
});
}
public reset() {
this._octokits = new Map<string, Octokit>();
this._authenticationStatusBarItems.forEach(statusBarItem => statusBarItem.dispose());
this._authenticationStatusBarItems = new Map<string, vscode.StatusBarItem>();
}
public async hasOctokit(remote: Remote): Promise<boolean> {
// the remote url might be http[s]/git/ssh but we always go through https for the api
// so use a normalized http[s] url regardless of the original protocol
const normalizedUri = remote.gitProtocol.normalizeUri();
const host = `${normalizedUri.scheme}://${normalizedUri.authority}`;
if (this._octokits.has(host)) {
return true;
}
this._configuration.setHost(host);
const creds: IHostConfiguration = this._configuration;
const server = new GitHubServer(host);
let octokit: Octokit;
if (creds.token) {
if (await server.validate(creds.username, creds.token)) {
octokit = this.createOctokit('token', creds);
}
}
if (octokit) {
this._octokits.set(host, octokit);
}
await this.updateAuthenticationStatusBar(remote);
return this._octokits.has(host);
}
public getOctokit(remote: Remote): Octokit {
const normalizedUri = remote.gitProtocol.normalizeUri();
const host = `${normalizedUri.scheme}://${normalizedUri.authority}`;
return this._octokits.get(host);
}
public async loginWithConfirmation(remote: Remote): Promise<Octokit> {
const normalizedUri = remote.gitProtocol.normalizeUri();
const result = await vscode.window.showInformationMessage(
`In order to use the Pull Requests functionality, you need to sign in to ${normalizedUri.authority}`,
SIGNIN_COMMAND);
if (result === SIGNIN_COMMAND) {
return await this.login(remote);
} else {
// user cancelled sign in, remember that and don't ask again
this._octokits.set(`${normalizedUri.scheme}://${normalizedUri.authority}`, undefined);
this._telemetry.on('auth.cancel');
}
}
public async login(remote: Remote): Promise<Octokit> {
this._telemetry.on('auth.start');
// the remote url might be http[s]/git/ssh but we always go through https for the api
// so use a normalized http[s] url regardless of the original protocol
const { scheme, authority } = remote.gitProtocol.normalizeUri();
const host = `${scheme}://${authority}`;
let retry: boolean = true;
let octokit: Octokit;
const server = new GitHubServer(host);
while (retry) {
try {
this.willStartLogin(authority);
const login = await server.login();
if (login) {
octokit = this.createOctokit('token', login);
await this._configuration.update(login.username, login.token, false);
vscode.window.showInformationMessage(`You are now signed in to ${authority}`);
}
} catch (e) {
Logger.appendLine(`Error signing in to ${authority}: ${e}`);
if (e instanceof Error) {
Logger.appendLine(e.stack);
}
} finally {
this.didEndLogin(authority);
}
if (octokit) {
retry = false;
} else if (retry) {
retry = (await vscode.window.showErrorMessage(`Error signing in to ${authority}`, TRY_AGAIN)) === TRY_AGAIN;
}
}
if (octokit) {
this._octokits.set(host, octokit);
this._telemetry.on('auth.success');
} else {
this._telemetry.on('auth.fail');
}
this.updateAuthenticationStatusBar(remote);
return octokit;
}
public isCurrentUser(username: string, remote: Remote): boolean {
const octokit = this.getOctokit(remote);
return octokit && (octokit as any).currentUser && (octokit as any).currentUser.login === username;
}
private createOctokit(type: string, creds: IHostConfiguration): Octokit {
const octokit = new Octokit({
baseUrl: `${HostHelper.getApiHost(creds).toString().slice(0, -1)}${HostHelper.getApiPath(creds, '')}`,
headers: { 'user-agent': 'GitHub VSCode Pull Requests' }
});
if (creds.token) {
if (type === 'token') {
octokit.authenticate({
type: 'token',
token: creds.token,
});
} else {
octokit.authenticate({
type: 'basic',
username: creds.username,
password: creds.token,
});
}
}
return octokit;
}
private async updateStatusBarItem(statusBarItem: vscode.StatusBarItem, remote: Remote): Promise<void> {
const octokit = this.getOctokit(remote);
let text: string;
let command: string;
if (octokit) {
try {
const user = await octokit.users.get({});
(octokit as any).currentUser = user.data;
text = `$(mark-github) ${user.data.login}`;
} catch (e) {
text = '$(mark-github) Signed in';
}
command = null;
} else {
const authority = remote.gitProtocol.normalizeUri().authority;
text = `$(mark-github) Sign in to ${authority}`;
command = 'pr.signin';
}
statusBarItem.text = text;
statusBarItem.command = command;
}
private willStartLogin(authority: string): void {
const status = this._authenticationStatusBarItems.get(authority);
status.text = `$(mark-github) Signing in to ${authority}...`;
status.command = AUTH_INPUT_TOKEN_CMD;
}
private didEndLogin(authority: string): void {
const status = this._authenticationStatusBarItems.get(authority);
status.text = `$(mark-github) Signed in to ${authority}`;
status.command = null;
}
private async updateAuthenticationStatusBar(remote: Remote): Promise<void> {
const authority = remote.gitProtocol.normalizeUri().authority;
const statusBarItem = this._authenticationStatusBarItems.get(authority);
if (statusBarItem) {
await this.updateStatusBarItem(statusBarItem, remote);
} else {
const newStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
this._authenticationStatusBarItems.set(authority, newStatusBarItem);
await this.updateStatusBarItem(newStatusBarItem, remote);
newStatusBarItem.show();
}
}
}