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
279 lines (237 loc) · 8.9 KB
/
credentials.ts
File metadata and controls
279 lines (237 loc) · 8.9 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
/*---------------------------------------------------------------------------------------------
* 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 { ApolloClient, InMemoryCache, NormalizedCacheObject, gql } from 'apollo-boost';
import { setContext } from 'apollo-link-context';
import * as vscode from 'vscode';
import { agent } from '../common/net';
import { IHostConfiguration, HostHelper } from '../authentication/configuration';
import { GitHubServer } from '../authentication/githubServer';
import { getToken, setToken } from '../authentication/keychain';
import { Remote } from '../common/remote';
import Logger from '../common/logger';
import { ITelemetry } from './interface';
import { handler as uriHandler } from '../common/uri';
import { createHttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
const TRY_AGAIN = 'Try again?';
const SIGNIN_COMMAND = 'Sign in';
const AUTH_INPUT_TOKEN_CMD = 'auth.inputTokenCallback';
export interface GitHub {
octokit: Octokit;
graphql: ApolloClient<NormalizedCacheObject> | null;
}
export class CredentialStore {
private _octokits: Map<string, GitHub | undefined>;
private _authenticationStatusBarItems: Map<string, vscode.StatusBarItem>;
constructor(private readonly _telemetry: ITelemetry) {
this._octokits = new Map<string, GitHub>();
this._authenticationStatusBarItems = new Map<string, vscode.StatusBarItem>();
vscode.commands.registerCommand(AUTH_INPUT_TOKEN_CMD, async () => {
const uriOrToken = await vscode.window.showInputBox({ prompt: 'Token' });
if (!uriOrToken) { return; }
try {
const uri = vscode.Uri.parse(uriOrToken);
if (!uri.scheme) { throw new Error; }
uriHandler.handleUri(uri);
} catch (error) {
// If it doesn't look like a URI, treat it as a token.
const host = await vscode.window.showInputBox({ prompt: 'Server', placeHolder: 'github.com' });
if (!host) { return; }
setToken(host, uriOrToken);
}
});
}
public reset() {
this._octokits = new Map<string, GitHub>();
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;
}
const server = new GitHubServer(host);
const token = await getToken(host);
let octokit: GitHub | undefined = undefined;
if (token) {
if (await server.validate(token)) {
octokit = await this.createHub({ host, token });
} else {
Logger.debug(`Token is no longer valid for host ${host}.`, 'Authentication');
}
} else {
Logger.debug(`No token found for host ${host}.`, 'Authentication');
}
if (octokit) {
this._octokits.set(host, octokit);
}
await this.updateAuthenticationStatusBar(remote);
return this._octokits.has(host);
}
public getHub(remote: Remote): GitHub | undefined {
const normalizedUri = remote.gitProtocol.normalizeUri()!;
const host = `${normalizedUri.scheme}://${normalizedUri.authority}`;
return this._octokits.get(host);
}
public getOctokit(remote: Remote): Octokit | undefined {
const hub = this.getHub(remote);
return hub && hub.octokit;
}
public getGraphQL(remote: Remote) {
const hub = this.getHub(remote);
return hub && hub.graphql;
}
public async loginWithConfirmation(remote: Remote): Promise<GitHub | undefined> {
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<GitHub | undefined> {
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: GitHub | undefined = undefined;
const server = new GitHubServer(host);
while (retry) {
try {
this.willStartLogin(authority);
const login = await server.login();
if (login && login.token) {
octokit = await this.createHub(login);
await setToken(login.host, login.token, { emit: 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 && e.stack) {
Logger.appendLine(e.stack);
}
} finally {
this.didEndLogin(authority);
}
if (octokit) {
retry = false;
} else {
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 async createHub(creds: IHostConfiguration): Promise<GitHub> {
const baseUrl = `${HostHelper.getApiHost(creds).toString().slice(0, -1)}${HostHelper.getApiPath(creds, '')}`;
let octokit = new Octokit({
agent,
baseUrl,
headers: { 'user-agent': 'GitHub VSCode Pull Requests' }
});
octokit.authenticate({
type: 'token',
token: creds.token || '',
});
const graphql = new ApolloClient({
link: link(baseUrl, creds.token || ''),
cache: new InMemoryCache,
defaultOptions: {
query: {
fetchPolicy: 'no-cache'
}
}
});
let supportsGraphQL = true;
await graphql.query({ query: gql `query { viewer { login } }` })
.then(result => {
Logger.appendLine(`${baseUrl}: GraphQL support detected`);
})
.catch(err => {
Logger.appendLine(`${baseUrl}: GraphQL not supported (${err.message})`);
supportsGraphQL = false;
});
return {
octokit,
graphql: supportsGraphQL ? graphql : null,
};
}
private async updateStatusBarItem(statusBarItem: vscode.StatusBarItem, remote: Remote): Promise<void> {
const octokit = this.getOctokit(remote);
let text: string;
let command: string | undefined;
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 = undefined;
} 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 = undefined;
}
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();
}
}
}
const link = (url: string, token: string) =>
setContext((_, { headers }) => (({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
}))).concat(createHttpLink({
uri: `${url}/graphql`,
// https://github.com/apollographql/apollo-link/issues/513
fetch: fetch as any
}));