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
194 lines (162 loc) · 6.18 KB
/
Copy pathcredentials.ts
File metadata and controls
194 lines (162 loc) · 6.18 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
/*---------------------------------------------------------------------------------------------
* 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';
const TRY_AGAIN = 'Try again?';
const SIGNIN_COMMAND = 'Sign in';
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>();
}
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);
}
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 normalizedUri = remote.gitProtocol.normalizeUri();
const host = `${normalizedUri.scheme}://${normalizedUri.authority}`;
let retry: boolean = true;
let octokit: Octokit;
const server = new GitHubServer(host);
while (retry) {
try {
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 ${normalizedUri.authority}`);
}
} catch (e) {
Logger.appendLine(`Error signing in to ${normalizedUri.authority}: ${e}`);
if (e instanceof Error) {
Logger.appendLine(e.stack);
}
}
if (octokit) {
retry = false;
} else if (retry) {
retry = (await vscode.window.showErrorMessage(`Error signing in to ${normalizedUri.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;
}
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({});
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 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();
}
}
}