-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathhttp.ts
More file actions
590 lines (520 loc) · 18 KB
/
Copy pathhttp.ts
File metadata and controls
590 lines (520 loc) · 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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Browser, User } from '@app/globals';
import { catchError, map, mergeMap, retry } from 'rxjs/operators';
import {
AdminConnectData,
Asset,
ConnectData,
ConnectionToken,
Endpoint,
Session,
Ticket,
TreeNode,
User as _User
} from '@app/model';
import { getCsrfTokenFromCookie, getQueryParamFromURL } from '@app/utils/common';
import { from, Observable, throwError } from 'rxjs';
import { I18nService } from '@app/services/i18n';
import { LoginExpiredDialogService } from '@app/services/dialog/login-expired.service';
import { CookieService } from 'ngx-cookie-service';
import { encryptPassword } from '@app/utils/crypto';
import { withSitePrefix } from '@app/utils/path';
@Injectable()
export class HttpService {
headers = new HttpHeaders();
constructor(
private http: HttpClient,
private _i18n: I18nService,
private _cookie: CookieService,
private _loginExpiredDialog: LoginExpiredDialogService
) {}
setOptionsCSRFToken(options) {
const csrfToken = getCsrfTokenFromCookie();
if (!options) {
options = {};
}
let headers = options.headers || new HttpHeaders();
headers = headers.set('X-CSRFToken', csrfToken);
options.headers = headers;
return options;
}
setOrgIDToRequestHeader(url, options) {
if (!options) {
options = {};
}
const headers = options.headers || new HttpHeaders();
if (!headers.get('X-JMS-ORG')) {
const orgID = this._cookie.get('X-JMS-LUNA-ORG') || this._cookie.get('X-JMS-ORG');
options.headers = headers.set('X-JMS-ORG', orgID);
}
return options;
}
getJMSOrg() {
return new HttpHeaders().set('X-JMS-ORG', this._cookie.get('X-JMS-ORG'));
}
private resolveUrl(url: string): string {
if (!url || typeof url !== 'string' || !url.startsWith('/')) {
return url;
}
return withSitePrefix(url);
}
get<T>(url: string, options?: any): Observable<any> {
const resolvedUrl = this.resolveUrl(url);
options = this.setOrgIDToRequestHeader(resolvedUrl, options);
return this.http.get(resolvedUrl, options).pipe(catchError(this.handleError.bind(this)));
}
handleError(error: HttpErrorResponse): Observable<never> {
if (error.status === 401 && User.logined) {
this._loginExpiredDialog.showLoginExpired();
} else if (error.status === 403) {
return from(this._i18n.t('No permission')).pipe(
mergeMap(msg => {
alert(msg);
return throwError(() => error);
})
);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(`Backend returned code ${error.status}, body was: `, error.error);
}
return throwError(() => error);
}
post<T>(url: string, body: any, options?: any): Observable<any> {
options = this.setOptionsCSRFToken(options);
return this.http
.post(this.resolveUrl(url), body, options)
.pipe(catchError(this.handleError.bind(this)));
}
put<T>(url: string, body?: any, options?: any): Observable<any> {
options = this.setOptionsCSRFToken(options);
return this.http
.put(this.resolveUrl(url), body, options)
.pipe(catchError(this.handleError.bind(this)));
}
delete<T>(url: string, options?: any): Observable<any> {
options = this.setOptionsCSRFToken(options);
return this.http
.delete(this.resolveUrl(url), options)
.pipe(catchError(this.handleError.bind(this)));
}
patch<T>(url: string, body?: any, options?: any): Observable<any> {
options = this.setOptionsCSRFToken(options);
return this.http
.patch(this.resolveUrl(url), body, options)
.pipe(catchError(this.handleError.bind(this)));
}
head<T>(url: string, options?: any) {
return this.http.head(this.resolveUrl(url), options);
}
options(url: string, options?: any) {
return this.http.options(this.resolveUrl(url), options);
}
reportBrowser() {
return this.post('/api/browser', JSON.stringify(Browser));
}
checkLogin(user: any) {
return this.post('/api/checklogin', user);
}
getPerms() {
const url = '/api/v1/users/profile/permissions/';
return this.get(url);
}
getProfile() {
let url = '/api/v1/users/profile/';
const connectionToken = getQueryParamFromURL('token');
if (connectionToken) {
// 解决 /luna/connect?connectToken= 直接方式权限认证问题
url += `?token=${connectionToken}`;
}
return this.get<ConnectionToken>(url);
}
async getUserProfile() {
const profile = this.getProfile().toPromise();
const perms = this.getPerms().toPromise();
const res = await Promise.all([profile, perms]);
return Object.assign({}, res[0], res[1]);
}
getUserSession() {
const url = '/api/v1/authentication/user-session/';
return this.get<_User>(url);
}
deleteUserSession() {
const url = '/api/v1/authentication/user-session/';
return this.delete<_User>(url);
}
getMyGrantedAssets(keyword) {
const url = `/api/v1/perms/users/self/assets/tree/?search=${keyword}`;
return this.get<Array<TreeNode>>(url);
}
filterMyGrantedAssetsById(id: string) {
const url = `/api/v1/perms/users/self/assets/tree/?id=${id}`;
return this.get<Array<TreeNode>>(url);
}
withRetry() {
return retry({
count: 10,
delay: 10000 // 每次重试间隔 10 秒(单位毫秒)
});
}
getMyGrantedNodes(async: boolean) {
const syncUrl = '/api/v1/perms/users/self/nodes/all-with-assets/tree/';
const asyncUrl = '/api/v1/perms/users/self/nodes/children-with-assets/tree/';
const url = async ? asyncUrl : syncUrl;
return this.get(url, { observe: 'response' }).pipe(this.withRetry());
}
getAssetTypeTree(async: boolean) {
const isSync = !async ? 1 : 0;
const url = `/api/v1/perms/users/self/nodes/children-with-assets/category/tree/?sync=${isSync}`;
return this.get<Array<TreeNode>>(url, { observe: 'response' }).pipe(this.withRetry());
}
getPermedAssetDetail(id) {
const url = `/api/v1/perms/users/self/assets/${id}/`;
return this.get<Asset>(url);
}
getAssetDetail(id) {
const url = `/api/v1/assets/assets/${id}/`;
return this.get<Asset>(url);
}
getAccountDetail(id) {
const url = `/api/v1/accounts/accounts/${id}/`;
return this.get<any>(url);
}
favoriteAsset(assetId: string, favorite: boolean) {
let url: string;
url = `/api/v1/assets/favorite-assets/`;
if (favorite) {
const data = {
asset: assetId
};
return this.post(url, data);
} else {
return this.delete(`${url}?asset=${assetId}`);
}
}
getFavoriteAssets() {
const url = '/api/v1/assets/favorite-assets/';
return this.get<Array<any>>(url);
}
/**
* Get all favorite folders of current user
*/
getFavoriteFolders() {
const url = '/api/v1/assets/favorite-folders/';
return this.get<Array<any>>(url);
}
/**
* Create a favorite folder
* @param name folder name
* @param parent parent folder id, null means a top-level folder
*/
createFavoriteFolder(name: string, parent: string = null) {
const url = '/api/v1/assets/favorite-folders/';
return this.post(url, { name, parent });
}
/**
* Delete a favorite folder (its favorite relations are cascade-removed by backend)
* @param folderId folder id
*/
deleteFavoriteFolder(folderId: string) {
const url = `/api/v1/assets/favorite-folders/${folderId}/`;
return this.delete(url);
}
/**
* Rename a favorite folder
* @param folderId folder id
* @param name new folder name
*/
updateFavoriteFolder(folderId: string, name: string) {
const url = `/api/v1/assets/favorite-folders/${folderId}/`;
return this.patch(url, { name });
}
/**
* Get favorite asset records inside a folder
* @param folderId folder id
*/
getFavoriteAssetsByFolder(folderId: string) {
const url = `/api/v1/assets/favorite-assets/?folder=${folderId}`;
return this.get<Array<any>>(url);
}
/**
* Favorite an asset into a folder
* @param assetId asset id
* @param folderId folder id
*/
favoriteAssetToFolder(assetId: string, folderId: string) {
const url = '/api/v1/assets/favorite-assets/';
return this.post(url, { asset: assetId, folder: folderId });
}
/**
* Remove an asset from a folder
* @param assetId asset id
* @param folderId folder id
*/
removeFavoriteFromFolder(assetId: string, folderId: string) {
const url = `/api/v1/assets/favorite-assets/?asset=${assetId}&folder=${folderId}`;
return this.delete(url);
}
search(q: string) {
const params = new HttpParams().set('q', q);
return this.get('/api/search', { params: params });
}
getReplay(sessionId: string) {
return this.get(`/api/v1/terminal/sessions/${sessionId}/replay/`, {
headers: this.getJMSOrg()
});
}
getPartFileReplay(sessionId: string, filename: string) {
const params = new HttpParams().set('part_filename', filename);
return this.get(`/api/v1/terminal/sessions/${sessionId}/replay/`, {
headers: this.getJMSOrg(),
params: params
});
}
getSessionDetail(sid: string): Promise<Session> {
return this.get<Session>(`/api/v1/terminal/sessions/${sid}/`, {
headers: this.getJMSOrg()
}).toPromise();
}
getReplayData(src: string) {
return this.get(src);
}
getCommandsData(sid: string, page: number) {
const params = new HttpParams()
.set('session_id', sid)
.set('limit', '30')
.set('offset', String(30 * page))
.set('order', 'timestamp');
return this.get('/api/v1/terminal/commands/', { params: params, headers: this.getJMSOrg() });
}
cleanRDPParams(params) {
const cleanedParams = {};
const { rdp_resolution, rdp_client_option, rdp_smart_size, rdp_color_quality } =
params.graphics;
if (rdp_resolution && rdp_resolution.indexOf('x') > -1) {
const [width, height] = rdp_resolution.split('x');
cleanedParams['width'] = width;
cleanedParams['height'] = height;
}
if (rdp_client_option.includes('full_screen')) {
cleanedParams['full_screen'] = '1';
}
if (rdp_client_option.includes('multi_screen')) {
cleanedParams['multi_mon'] = '1';
}
if (rdp_client_option.includes('drives_redirect')) {
cleanedParams['drives_redirect'] = '1';
}
cleanedParams['rdp_smart_size'] = rdp_smart_size;
cleanedParams['rdp_color_quality'] = rdp_color_quality;
return cleanedParams;
}
getFaceVerifyState(token: string) {
const url = `/api/v1/authentication/face/context/?token=${token}`;
return this.get(url);
}
createConnectToken(
asset: Asset,
connectData: ConnectData,
createTicket = false,
face_verify = false,
face_monitor_token?: string
) {
let params = createTicket ? '?create_ticket=1' : '';
params += face_verify ? '?face_verify=1' : '';
params += face_monitor_token ? `&face_monitor_token=${face_monitor_token}` : '';
const url = '/api/v1/authentication/connection-token/' + params;
const { account, protocol, manualAuthInfo, connectMethod } = connectData;
const isVirtual = account.username.startsWith('@');
const username = isVirtual ? manualAuthInfo.username : account.username;
const secret = encryptPassword(manualAuthInfo.secret);
const connectOption = { ...(connectData.connectOption || {}) };
// 始终以当前表单为准,避免 connectOption 里残留上一次的 input_secret_type
const inputSecretType =
(manualAuthInfo && manualAuthInfo['input_secret_type']) || 'password';
const data = {
asset: asset.id,
account: account.alias, // 主要是有特殊账号,匿名、虚拟
protocol: protocol.name,
input_username: username,
input_secret: secret,
input_secret_type: inputSecretType,
connect_method: connectMethod.value,
connect_options: connectOption
};
return this.post<ConnectionToken>(url, data).pipe(
catchError(this.handleConnectMethodExpiredError.bind(this))
);
}
directiveConnect(assetId: String) {
const url = `/api/v1/assets/assets/${assetId}/`;
return this.get(url);
}
adminConnectToken(
asset: Asset,
connectData: AdminConnectData,
createTicket = false,
face_verify = false,
face_monitor_token?: string
) {
let params = '';
params += createTicket ? '?create_ticket=1' : '';
params += face_verify ? '?face_verify=1' : '';
params += face_monitor_token ? `&face_monitor_token=${face_monitor_token}` : '';
const url = '/api/v1/authentication/admin-connection-token/' + params;
const { account, protocol } = connectData;
const connectOption = connectData.connectOption || {};
const data = {
asset: asset.id,
account: account.id,
protocol: protocol.name,
input_username: connectData.input_username,
connect_method: connectData.method || connectData.connectMethod.value,
connect_options: connectOption
};
return this.post<ConnectionToken>(url, data).pipe(
catchError(this.handleConnectMethodExpiredError.bind(this))
);
}
exchangeConnectToken(
tokenID: string,
createTicket = false,
face_verify = false,
face_monitor_token?: string
) {
let params = createTicket ? '?create_ticket=1' : '';
params += face_verify ? '?face_verify=1' : '';
params += face_monitor_token ? `&face_monitor_token=${face_monitor_token}` : '';
const url = '/api/v1/authentication/connection-token/exchange/' + params;
const data = { id: tokenID };
return this.post<ConnectionToken>(url, data);
}
getConnectToken(token) {
const url = new URL(
withSitePrefix(`/api/v1/authentication/connection-token/${token}/`),
window.location.origin
);
return this.get(url.href);
}
downloadRDPFile(token, params: Object, connectOption: any) {
const url = new URL(
withSitePrefix(`/api/v1/authentication/connection-token/${token.id}/rdp-file/`),
window.location.origin
);
params = this.cleanRDPParams(params);
if (params) {
for (const [k, v] of Object.entries(params)) {
url.searchParams.append(k, v);
}
}
if (connectOption && connectOption.reusable) {
url.searchParams.append('reusable', '1');
}
if (connectOption && connectOption.remote_microphone !== undefined) {
url.searchParams.append('remote_microphone', connectOption.remote_microphone ? '1' : '0');
}
return window.open(url.href);
}
getLocalClientUrl(token, params: Object = {}) {
const url = new URL(
withSitePrefix(`/api/v1/authentication/connection-token/${token.id}/client-url/`),
window.location.origin
);
params = this.cleanRDPParams(params);
if (params) {
for (const [k, v] of Object.entries(params)) {
url.searchParams.append(k, v);
}
}
return this.get(url.href).pipe(catchError(this.handleConnectMethodExpiredError.bind(this)));
}
getLocalClientUrlAndSetCommand(token, command: string, params: Object = {}) {
const setCommand = res => {
const protocol = 'jms://';
const buf = res.url.replace(protocol, '');
const bufObj = JSON.parse(window.atob(buf));
bufObj['command'] = command;
const bufStr = window.btoa(JSON.stringify(bufObj));
res.url = protocol + bufStr;
return res;
};
return new Promise((resolve, reject) => {
this.getLocalClientUrl(token, params).subscribe(
res => resolve(setCommand(res)),
err => reject(err)
);
});
}
async handleConnectMethodExpiredError(error) {
if (error.status === 400) {
if (error.error && error.error.error && error.error.error.startsWith('Connect method')) {
const errMsg = await this._i18n.t(
'The connection method is invalid, please refresh the page'
);
alert(errMsg);
}
}
throw error;
}
getSmartEndpoint({ assetId, sessionId, token }, protocol): Promise<Endpoint> {
const url = new URL(withSitePrefix('/api/v1/terminal/endpoints/smart/'), window.location.origin);
url.searchParams.append('protocol', protocol);
if (assetId) {
url.searchParams.append('asset_id', assetId);
} else if (sessionId) {
url.searchParams.append('session_id', sessionId);
} else if (token) {
url.searchParams.append('token', token);
}
return this.get(url.href)
.pipe(map(res => Object.assign(new Endpoint(), res)))
.toPromise();
}
getTicketDetail(ticketId: string): Promise<Ticket> {
const url = `/api/v1/tickets/tickets/${ticketId}/`;
return this.get<Ticket>(url).toPromise();
}
toggleLockSession(sessionId: string, lock: boolean): Promise<any> {
const url = `/api/v1/terminal/tasks/toggle-lock-session/`;
const taskName = lock ? 'lock_session' : 'unlock_session';
const data = {
session_id: sessionId,
task_name: taskName
};
return this.post(url, data).toPromise();
}
toggleLockSessionForTicket(ticketId: string, sessionId: string, lock: boolean): Promise<any> {
const url = `/api/v1/terminal/tasks/toggle-lock-session-for-ticket/`;
const taskName = lock ? 'lock_session' : 'unlock_session';
const data = {
session_id: sessionId,
task_name: taskName
};
return this.post(url, data).toPromise();
}
getQuickCommand() {
const url = '/api/v1/ops/adhocs/?only_mine=true';
return this.get(url).toPromise();
}
addQuickCommand(data) {
const url = '/api/v1/ops/adhocs/';
return this.post(url, data);
}
getSessionOnlineNum(assetId: string, account: string) {
const url = `/api/v1/terminal/sessions/online-info/?asset_id=${assetId}&account=${account}`;
return this.get(url);
}
getUserDetail(uid: string): Promise<_User> {
const url = `/api/v1/users/users/${uid}/`;
return this.get<_User>(url).toPromise();
}
getShareUserList(keyword: string) {
const url = `/api/v1/users/users/?search=${keyword}`;
return this.get<Array<_User>>(url);
}
setTerminalPreference(data) {
const url = '/api/v1/users/preference/?category=luna';
return this.patch(url, data);
}
}