-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathauth-handler.ts
More file actions
442 lines (398 loc) · 15.3 KB
/
auth-handler.ts
File metadata and controls
442 lines (398 loc) · 15.3 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import cliux from './cli-ux';
import configHandler from './config-handler';
import dotenv from 'dotenv';
import open from 'open';
import http from 'http';
import url from 'url';
import { handleAndLogError } from './logger/log';
import managementSDKClient, { ContentstackClient } from './contentstack-management-sdk';
import { formatError } from './helpers';
dotenv.config();
/**
* @class
* Auth handler
*/
class AuthHandler {
private _host;
private OAuthBaseURL: string;
private OAuthAppId: string;
private OAuthClientId: string;
private OAuthRedirectURL: string;
private OAuthScope: string[];
private OAuthResponseType: string;
private authTokenKeyName: string;
private authEmailKeyName: string;
private oauthAccessTokenKeyName: string;
private oauthDateTimeKeyName: string;
private oauthUserUidKeyName: string;
private oauthOrgUidKeyName: string;
private oauthRefreshTokenKeyName: string;
private authorisationTypeKeyName: string;
private authorisationTypeOAUTHValue: string;
private authorisationTypeAUTHValue: string;
private allAuthConfigItems: any;
private oauthHandler: any;
private managementAPIClient: ContentstackClient;
/** True while an OAuth access-token refresh is running (for logging/diagnostics; correctness uses `oauthRefreshInFlight`). */
private isRefreshingToken: boolean = false; // Flag to track if a refresh operation is in progress
/** Serialize OAuth refresh so concurrent API calls await the same refresh instead of proceeding with a stale token. */
private oauthRefreshInFlight: Promise<void> | null = null;
private cmaHost: string;
set host(contentStackHost) {
this._host = contentStackHost;
// Update cmaHost when host is set
this.cmaHost = this.getCmaHost();
}
constructor() {
this.OAuthAppId = process.env.OAUTH_APP_ID || '6400aa06db64de001a31c8a9';
this.OAuthClientId = process.env.OAUTH_CLIENT_ID || 'Ie0FEfTzlfAHL4xM';
this.OAuthRedirectURL = process.env.OAUTH_APP_REDIRECT_URL || 'http://localhost:8184';
this.OAuthScope = [];
this.OAuthResponseType = 'code';
this.authTokenKeyName = 'authtoken';
this.authEmailKeyName = 'email';
this.oauthAccessTokenKeyName = 'oauthAccessToken';
this.oauthDateTimeKeyName = 'oauthDateTime';
this.oauthUserUidKeyName = 'userUid';
this.oauthOrgUidKeyName = 'oauthOrgUid';
this.oauthRefreshTokenKeyName = 'oauthRefreshToken';
this.authorisationTypeKeyName = 'authorisationType';
this.authorisationTypeOAUTHValue = 'OAUTH';
this.authorisationTypeAUTHValue = 'BASIC';
this.allAuthConfigItems = {
refreshToken: [
this.authTokenKeyName,
this.oauthAccessTokenKeyName,
this.oauthDateTimeKeyName,
this.oauthRefreshTokenKeyName,
],
default: [
this.authTokenKeyName,
this.authEmailKeyName,
this.oauthAccessTokenKeyName,
this.oauthDateTimeKeyName,
this.oauthUserUidKeyName,
this.oauthOrgUidKeyName,
this.oauthRefreshTokenKeyName,
this.authorisationTypeKeyName,
],
};
this.cmaHost = this.getCmaHost();
}
private getCmaHost(): string {
if (this._host) {
return this._host;
}
const cma = configHandler.get('region')?.cma;
if (cma && cma.startsWith('http')) {
try {
const u = new URL(cma);
if (u.host) return u.host;
} catch (error) {
// If URL parsing fails, return the original cma value
}
}
return cma;
}
async setOAuthBaseURL() {
if (configHandler.get('region')['uiHost']) {
this.OAuthBaseURL = configHandler.get('region')['uiHost'] || '';
} else {
throw new Error(
'Invalid ui-host URL while authenticating. Please set your region correctly using the command - csdx config:set:region',
);
}
}
async initSDK() {
// Ensure we have a valid host for the SDK initialization
const host = this._host || this.getCmaHost();
this.managementAPIClient = await managementSDKClient({ host });
this.oauthHandler = this.managementAPIClient.oauth({
appId: this.OAuthAppId,
clientId: this.OAuthClientId,
redirectUri: this.OAuthRedirectURL,
scope: this.OAuthScope,
responseType: this.OAuthResponseType,
});
this.restoreOAuthConfig();
}
/*
*
* Login into Contentstack
* @returns {Promise} Promise object returns {} on success
*/
async oauth(): Promise<void> {
try {
await this.initSDK();
await this.createHTTPServer();
await this.openOAuthURL();
} catch (error) {
handleAndLogError(error, { module: 'auth-handler' }, 'OAuth login failed!');
throw error;
}
}
async createHTTPServer(): Promise<void> {
try {
const server = http.createServer(async (req, res) => {
const queryObject = url.parse(req.url, true).query;
if (!queryObject.code) {
cliux.error('Error occurred while logging in with OAuth!');
return sendErrorResponse(res);
}
cliux.print('Auth code successfully fetched.');
try {
await this.getAccessToken(queryObject.code as string);
await this.setOAuthBaseURL();
cliux.print('Access token successfully fetched using auth code.');
cliux.print(
`You can review the access permissions on the page - ${this.OAuthBaseURL}/#!/marketplace/authorized-apps`,
);
sendSuccessResponse(res);
stopServer();
} catch (error) {
cliux.error('Error occurred while logging in with OAuth!');
cliux.error(error);
sendErrorResponse(res);
stopServer();
}
});
const sendSuccessResponse = (res: any) => {
const successHtml = `
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 100px; }
p { color: #475161; margin-bottom: 20px; }
p button { background-color: #6c5ce7; color: #fff; border: 1px solid transparent; border-radius: 4px; font-weight: 600; line-height: 100%; text-align: center; min-height: 2rem; padding: 0.3125rem 1rem; }
</style>
<h1 style="color: #6c5ce7">Successfully authorized!</h1>
<p style="color: #475161; font-size: 16px; font-weight: 600">You can close this window now.</p>
<p>
You can review the access permissions on the
<a style="color: #6c5ce7; text-decoration: none" href="${this.OAuthBaseURL}/#!/marketplace/authorized-apps" target="_blank">Authorized Apps page</a>.
</p>`;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(successHtml);
};
const sendErrorResponse = (res: any) => {
const errorHtml = `
<h1>Sorry!</h1><h2>Something went wrong, please login with command.</h2>`;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(errorHtml);
};
const stopServer = () => {
server.close();
process.exit();
};
server.listen(8184, () => {
cliux.print('Waiting for the authorization server to respond...');
return { true: true };
});
// Listen for errors
server.on('error', (err) => {
cliux.error('Server encountered an error:', formatError(err));
});
} catch (error) {
cliux.error(error);
throw error;
}
}
async openOAuthURL(): Promise<void> {
try {
const url = await this.oauthHandler.authorize();
cliux.print(
'This will automatically start the browser and open the below URL, if it does not, you can copy and paste the below URL in the browser without terminating this command.',
{ color: 'yellow' },
);
cliux.print(url, { color: 'green' });
await open(url);
} catch (error) {
throw error;
}
}
async getAccessToken(code: string): Promise<void> {
try {
const data = await this.oauthHandler.exchangeCodeForToken(code);
const userData = await this.getUserDetails(data);
if (userData['access_token'] && userData['refresh_token']) {
await this.setConfigData('oauth', userData);
} else {
throw new Error('Invalid request');
}
} catch (error) {
cliux.error('An error occurred while fetching the access token, run the command - csdx auth:login --oauth');
cliux.error(error);
throw error;
}
}
async setConfigData(type: string, userData: any = {}): Promise<object> {
try {
this.unsetConfigData(type);
switch (type) {
case 'oauth':
case 'refreshToken':
if (userData.access_token && userData.refresh_token) {
this.setOAuthConfigData(userData, type);
return userData;
} else {
throw new Error('Invalid request');
}
case 'basicAuth':
if (userData.authtoken && userData.email) {
this.setBasicAuthConfigData(userData);
return userData;
} else {
throw new Error('Invalid request');
}
case 'logout':
return userData;
default:
throw new Error('Invalid request');
}
} catch (error) {
throw error;
}
}
setOAuthConfigData(userData: any, type: string) {
configHandler.set(this.oauthAccessTokenKeyName, userData.access_token);
configHandler.set(this.oauthRefreshTokenKeyName, userData.refresh_token);
configHandler.set(this.oauthDateTimeKeyName, new Date());
if (type === 'oauth') {
configHandler.set(this.authEmailKeyName, userData.email);
configHandler.set(this.oauthUserUidKeyName, userData.user_uid);
configHandler.set(this.oauthOrgUidKeyName, userData.organization_uid);
configHandler.set(this.authorisationTypeKeyName, this.authorisationTypeOAUTHValue);
}
}
setBasicAuthConfigData(userData: any) {
configHandler.set(this.authTokenKeyName, userData.authtoken);
configHandler.set(this.authEmailKeyName, userData.email);
configHandler.set(this.authorisationTypeKeyName, this.authorisationTypeAUTHValue);
}
unsetConfigData(type = 'default') {
const removeItems =
type === 'refreshToken' ? this.allAuthConfigItems.refreshToken : this.allAuthConfigItems.default;
removeItems.forEach((element) => configHandler.delete(element));
}
async refreshToken(): Promise<object> {
try {
if (!this.oauthHandler) {
await this.initSDK(); // Initialize oauthHandler if not already initialized
}
const configOauthRefreshToken = configHandler.get(this.oauthRefreshTokenKeyName);
const configAuthorisationType = configHandler.get(this.authorisationTypeKeyName);
if (configAuthorisationType !== this.authorisationTypeOAUTHValue || !configOauthRefreshToken) {
cliux.error('Invalid refresh token, run the command- csdx auth:login --oauth');
throw new Error('Invalid refresh token');
}
const data = await this.oauthHandler.refreshAccessToken(configOauthRefreshToken);
if (data['access_token'] && data['refresh_token']) {
await this.setConfigData('refreshToken', data);
return data; // Returning the data from the refresh token operation
} else {
throw new Error('Invalid request');
}
} catch (error) {
cliux.error('An error occurred while refreshing the token');
cliux.error(error);
throw error; // Throwing the error to be handled by the caller
}
}
async getUserDetails(data): Promise<object> {
if (data.access_token) {
try {
const user = await this.managementAPIClient.getUser();
data.email = user?.email || '';
return data;
} catch (error) {
cliux.error('Error fetching user details.');
cliux.error(error);
throw error;
}
} else {
cliux.error('Invalid or empty access token.');
throw new Error('Invalid or empty access token.');
}
}
async oauthLogout(): Promise<object> {
try {
if (!this.oauthHandler) {
await this.initSDK();
}
const response = await this.oauthHandler.logout();
return response || {};
} catch (error) {
cliux.error('An error occurred while logging out');
cliux.error(error);
throw error;
}
}
isAuthenticated(): boolean {
const authorizationType = configHandler.get(this.authorisationTypeKeyName);
return (
authorizationType === this.authorisationTypeOAUTHValue || authorizationType === this.authorisationTypeAUTHValue
);
}
async getAuthorisationType(): Promise<any> {
return configHandler.get(this.authorisationTypeKeyName) ? configHandler.get(this.authorisationTypeKeyName) : false;
}
async isAuthorisationTypeBasic(): Promise<boolean> {
return configHandler.get(this.authorisationTypeKeyName) === this.authorisationTypeAUTHValue ? true : false;
}
async isAuthorisationTypeOAuth(): Promise<boolean> {
return configHandler.get(this.authorisationTypeKeyName) === this.authorisationTypeOAUTHValue ? true : false;
}
checkExpiryAndRefresh = (force: boolean = false) => this.compareOAuthExpiry(force);
async compareOAuthExpiry(force: boolean = false) {
const oauthDateTime = configHandler.get(this.oauthDateTimeKeyName);
const authorisationType = configHandler.get(this.authorisationTypeKeyName);
if (oauthDateTime && authorisationType === this.authorisationTypeOAUTHValue) {
const now = new Date();
const oauthDate = new Date(oauthDateTime);
const oauthValidUpto = new Date(oauthDate.getTime() + 59 * 60 * 1000);
const tokenExpired = oauthValidUpto <= now;
const shouldRefresh = force || tokenExpired;
if (!shouldRefresh) {
return Promise.resolve();
}
if (this.oauthRefreshInFlight) {
return this.oauthRefreshInFlight;
}
this.isRefreshingToken = true;
this.oauthRefreshInFlight = (async () => {
try {
if (force) {
cliux.print('Forcing token refresh...');
} else {
cliux.print('Token expired, refreshing the token');
}
await this.refreshToken();
} catch (error) {
cliux.error('Error refreshing token');
throw error;
} finally {
this.isRefreshingToken = false;
this.oauthRefreshInFlight = null;
}
})();
return this.oauthRefreshInFlight;
} else {
cliux.print('No OAuth configuration set.');
this.unsetConfigData();
return Promise.resolve();
}
}
restoreOAuthConfig() {
const oauthAccessToken = configHandler.get(this.oauthAccessTokenKeyName);
const oauthRefreshToken = configHandler.get(this.oauthRefreshTokenKeyName);
const oauthDateTime = configHandler.get(this.oauthDateTimeKeyName);
const oauthUserUid = configHandler.get(this.oauthUserUidKeyName);
const oauthOrgUid = configHandler.get(this.oauthOrgUidKeyName);
if (oauthAccessToken && !this.oauthHandler.getAccessToken()) this.oauthHandler.setAccessToken(oauthAccessToken);
if (oauthRefreshToken && !this.oauthHandler.getRefreshToken()) this.oauthHandler.setRefreshToken(oauthRefreshToken);
if (oauthUserUid && !this.oauthHandler.getUserUID()) this.oauthHandler.setUserUID(oauthUserUid);
if (oauthOrgUid && !this.oauthHandler.getOrganizationUID()) this.oauthHandler.setOrganizationUID(oauthOrgUid);
if (oauthDateTime && !this.oauthHandler.getTokenExpiryTime()) {
this.oauthHandler.setTokenExpiryTime(oauthDateTime);
}
}
}
export default new AuthHandler();