-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathutils.ts
251 lines (217 loc) · 6.78 KB
/
utils.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
import { BrowserWindow } from '@electron/remote';
import { format } from 'date-fns';
import log from 'electron-log';
import type {
Account,
AuthCode,
AuthState,
ClientID,
GitifyUser,
Hostname,
Link,
Token,
} from '../../types';
import type { UserDetails } from '../../typesGitHub';
import { getAuthenticatedUser } from '../api/client';
import { apiRequest } from '../api/request';
import { Constants } from '../constants';
import { getPlatformFromHostname } from '../helpers';
import type { AuthMethod, AuthResponse, AuthTokenResponse } from './types';
// TODO - Refactor our OAuth2 flow to use system browser and local app gitify://callback - see #485 #561 #654
export function authGitHub(
authOptions = Constants.DEFAULT_AUTH_OPTIONS,
): Promise<AuthResponse> {
return new Promise((resolve, reject) => {
// Build the OAuth consent page URL
const authWindow = new BrowserWindow({
width: 548,
height: 736,
show: true,
});
const authUrl = new URL(`https://${authOptions.hostname}`);
authUrl.pathname = '/login/oauth/authorize';
authUrl.searchParams.append('client_id', authOptions.clientId);
authUrl.searchParams.append('scope', Constants.AUTH_SCOPE.toString());
const session = authWindow.webContents.session;
session.clearStorageData();
authWindow.loadURL(authUrl.toString());
const handleCallback = (url: Link) => {
const raw_code = /code=([^&]*)/.exec(url) || null;
const authCode =
raw_code && raw_code.length > 1 ? (raw_code[1] as AuthCode) : null;
const error = /\?error=(.+)$/.exec(url);
if (authCode || error) {
// Close the browser if code found or error
authWindow.destroy();
}
// If there is a code, proceed to get token from github
if (authCode) {
resolve({ authCode, authOptions });
} else if (error) {
reject(
"Oops! Something went wrong and we couldn't " +
'log you in using GitHub. Please try again.',
);
}
};
// If "Done" button is pressed, hide "Loading"
authWindow.on('close', () => {
authWindow.destroy();
});
authWindow.webContents.on(
'did-fail-load',
(_event, _errorCode, _errorDescription, validatedURL) => {
if (validatedURL.includes(authOptions.hostname)) {
authWindow.destroy();
reject(
`Invalid Hostname. Could not load https://${authOptions.hostname}/.`,
);
}
},
);
authWindow.webContents.on('will-redirect', (event, url) => {
event.preventDefault();
handleCallback(url as Link);
});
authWindow.webContents.on('will-navigate', (event, url) => {
event.preventDefault();
handleCallback(url as Link);
});
});
}
export async function getUserData(
token: Token,
hostname: Hostname,
): Promise<GitifyUser> {
const response: UserDetails = (await getAuthenticatedUser(hostname, token))
.data;
return {
id: response.id,
login: response.login,
name: response.name,
avatar: response.avatar_url as Link,
};
}
export async function getToken(
authCode: AuthCode,
authOptions = Constants.DEFAULT_AUTH_OPTIONS,
): Promise<AuthTokenResponse> {
const url =
`https://${authOptions.hostname}/login/oauth/access_token` as Link;
const data = {
client_id: authOptions.clientId,
client_secret: authOptions.clientSecret,
code: authCode,
};
const response = await apiRequest(url, 'POST', data);
return {
hostname: authOptions.hostname,
token: response.data.access_token,
};
}
export async function addAccount(
auth: AuthState,
method: AuthMethod,
token: Token,
hostname: Hostname,
): Promise<AuthState> {
let newAccount = {
hostname: hostname,
method: method,
platform: getPlatformFromHostname(hostname),
token: token,
} as Account;
newAccount = await refreshAccount(newAccount);
return {
accounts: [...auth.accounts, newAccount],
};
}
export function removeAccount(auth: AuthState, account: Account): AuthState {
const updatedAccounts = auth.accounts.filter(
(a) => a.token !== account.token,
);
return {
accounts: updatedAccounts,
};
}
export async function refreshAccount(account: Account): Promise<Account> {
try {
const res = await getAuthenticatedUser(account.hostname, account.token);
// Refresh user data
account.user = {
id: res.data.id,
login: res.data.login,
name: res.data.name,
avatar: res.data.avatar_url as Link,
};
// Refresh platform version
account.version = res.headers['x-github-enterprise-version'] ?? 'latest';
} catch (error) {
log.error('Failed to refresh account', error);
}
return account;
}
export function getDeveloperSettingsURL(account: Account): Link {
const settingsURL = new URL(`https://${account.hostname}`);
switch (account.method) {
case 'GitHub App':
settingsURL.pathname = '/settings/apps';
break;
case 'OAuth App':
settingsURL.pathname = '/settings/developers';
break;
case 'Personal Access Token':
settingsURL.pathname = '/settings/tokens';
break;
default:
settingsURL.pathname = '/settings';
break;
}
return settingsURL.toString() as Link;
}
export function getNewTokenURL(hostname: Hostname): Link {
const date = format(new Date(), 'PP p');
const newTokenURL = new URL(`https://${hostname}/settings/tokens/new`);
newTokenURL.searchParams.append('description', `Gitify (Created on ${date})`);
newTokenURL.searchParams.append('scopes', Constants.AUTH_SCOPE.join(','));
return newTokenURL.toString() as Link;
}
export function getNewOAuthAppURL(hostname: Hostname): Link {
const date = format(new Date(), 'PP p');
const newOAuthAppURL = new URL(
`https://${hostname}/settings/applications/new`,
);
newOAuthAppURL.searchParams.append(
'oauth_application[name]',
`Gitify (Created on ${date})`,
);
newOAuthAppURL.searchParams.append(
'oauth_application[url]',
'https://www.gitify.io',
);
newOAuthAppURL.searchParams.append(
'oauth_application[callback_url]',
'https://www.gitify.io/callback',
);
return newOAuthAppURL.toString() as Link;
}
export function isValidHostname(hostname: Hostname) {
return /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/i.test(
hostname,
);
}
export function isValidClientId(clientId: ClientID) {
return /^[A-Z0-9_]{20}$/i.test(clientId);
}
export function isValidToken(token: Token) {
return /^[A-Z0-9_]{40}$/i.test(token);
}
export function getAccountUUID(account: Account): string {
return btoa(`${account.hostname}-${account.user.id}-${account.method}`);
}
export function hasAccounts(auth: AuthState) {
return auth.accounts.length > 0;
}
export function hasMultipleAccounts(auth: AuthState) {
return auth.accounts.length > 1;
}