-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathconnect.component.ts
More file actions
605 lines (543 loc) · 15.6 KB
/
Copy pathconnect.component.ts
File metadata and controls
605 lines (543 loc) · 15.6 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { View, Account, AuthInfo, ConnectionToken, ConnectMethod, Endpoint } from '@app/model';
import { Component, OnInit, OnDestroy, ElementRef, ViewChildren, QueryList } from '@angular/core';
import { ElementACLDialogComponent } from '@src/app/services/connect-token/acl-dialog/acl-dialog.component';
import {
LogService,
AppService,
ViewService,
I18nService,
HttpService,
DrawerStateService,
IframeCommunicationService
} from '@app/services';
import { CookieService } from 'ngx-cookie-service';
import { Protocol } from '@app/model';
@Component({
standalone: false,
selector: 'pages-connect',
templateUrl: 'connect.component.html',
styleUrls: ['connect.component.scss']
})
export class PagesConnectComponent implements OnInit, OnDestroy {
@ViewChildren('contentWindow') contentWindows: QueryList<ElementRef>;
view: View;
public startTime: Date;
public totalConnectTime: string = '00:00:00';
public isActive: boolean = true;
public isTimerStopped: boolean = false;
public showActionIcons: boolean = false;
private readonly guiComponents: Set<string> = new Set(['lion', 'tinker', 'razor', 'panda']);
private readonly terminalComponents: Set<string> = new Set(['koko', 'chen', 'magnus', 'nec']);
// Direct 模式相关属性
public endpoint: Endpoint;
public assetId: string = '';
public org_id: string = '';
public username: string = '';
public protocol: string = '';
public accountId: string = '';
public assetName: string = '';
public isDirect: boolean = false;
public disabledOpenFileManage: boolean = false;
private timerInterval: any;
private pausedElapsedTime: number = 0;
private subscription: Subscription;
// Direct 模式私有属性
private permedAsset: any;
private connectData: any;
private account: Account;
private connectToken: ConnectionToken;
private connectMethod: ConnectMethod | string;
private asset: any;
private method: string;
private permedProtocol: Protocol;
constructor(
private _i18n: I18nService,
private _http: HttpService,
private _appSvc: AppService,
private _logger: LogService,
private _viewSrv: ViewService,
private _route: ActivatedRoute,
private _cookie: CookieService,
private _dialog: NzModalService,
private _drawerStateService: DrawerStateService,
private _iframeCommunicationService: IframeCommunicationService
) {
this.startTime = new Date();
}
async ngOnInit() {
this.view = null;
this.isTimerStopped = false;
this.checkDirectMode();
this.subscription = this._iframeCommunicationService.message$.subscribe(message => {
if (message.name === 'CLOSE') {
this.stopTimer();
}
});
if (this.isDirect) {
await this.initDirectMode();
} else {
this.handleEventChangeTime();
}
}
ngOnDestroy() {
this.stopTimer();
if (this.subscription) {
this.subscription.unsubscribe();
}
document.removeEventListener('mousemove', this.handleMouseMove.bind(this));
}
/**
* 检查是否为直连模式
*/
private checkDirectMode() {
const params = this._route.snapshot.queryParams;
// 检查是否有 direct: true 参数,或者同时有 account, asset, protocol 参数
this.isDirect =
params['direct'] === 'true' || !!(params['account'] && params['asset'] && params['protocol']);
if (this.isDirect) {
this.accountId = params['account'];
this.assetId = params['asset'];
this.protocol = params['protocol'];
this.org_id = params['org_id'];
this._cookie.set('X-JMS-LUNA-ORG', this.org_id, 30, '/');
this._logger.info('Direct mode detected', {
accountId: this.accountId,
assetId: this.assetId,
protocol: this.protocol,
fromPAM: params['direct'] === 'true'
});
}
}
/**
* 初始化直连模式
*/
private async initDirectMode() {
this._logger.info('DirectComponent initialized');
await this.getConnectData();
this._logger.info('DirectComponent getConnectData', this.asset);
const finish = await this.createConnectionToken();
if (finish) {
this.onNewView();
this.startTimer();
this.handleEventChangeTime();
}
}
/**
* 获取连接数据(直连模式)
*/
async getConnectData() {
this.asset = await this._http.getAssetDetail(this.assetId).toPromise();
this.account = await this._http.getAccountDetail(this.accountId).toPromise();
// const permed = await this._http.getPermedAssetDetail(this.assetId).toPromise();
this.permedProtocol = this.asset.protocols;
if (!this.asset) {
alert(this._i18n.instant('NoAsset'));
return;
}
this.assetName = this.asset.name;
this.method = this.getMethodByProtocol(this.protocol);
}
/**
* 创建连接令牌(直连模式)
*/
async createConnectionToken() {
const asset = this.asset;
this.permedAsset = {
id: this.assetId,
name: this.assetName,
address: asset.address,
comment: asset.comment,
type: asset.type,
category: asset.category,
permed_protocols: this.permedProtocol,
permed_accounts: asset.accounts,
spec_info: asset.spec_info
};
this.connectData = {
method: this.method,
protocol: { name: this.protocol },
asset: this.permedAsset,
account: this.account,
autoLogin: true,
input_username: this.account.username,
connectMethod: this.connectMethod,
manualAuthInfo: new AuthInfo(),
direct: true
};
this._appSvc.setPreConnectData(this.asset, this.connectData);
const res = await this.getConnectToken(this.permedAsset, this.connectData);
if (res) {
return res;
}
return new Promise((resolve, reject) => {
if (res) {
resolve(res);
} else {
reject(new Error('Failed to get connect token'));
}
});
}
/**
* 获取连接令牌
*/
private getConnectToken(assetMessage: any, connectData: any) {
return new Promise(async (resolve, reject) => {
try {
this._http.adminConnectToken(assetMessage, connectData, false, false, '').subscribe(
res => {
this.connectToken = res;
resolve(true);
},
error => {
const dialogRef = this._dialog.create({
nzContent: ElementACLDialogComponent,
nzData: {
asset: assetMessage,
connectData: connectData,
code: error.error.code,
tokenAction: 'create',
error: error
}
});
dialogRef.afterClose.subscribe(token => {
if (token) {
this.connectToken = token;
this.onNewView();
this.startTimer();
return;
}
window.close();
});
}
);
} catch (error) {
this._logger.error('Failed to get connect token:', error);
reject(error);
}
});
}
/**
* 根据协议确定连接方法
*/
private getMethodByProtocol(protocol: string): string {
const endpointProtocol = window.location.protocol.replace(':', '');
switch (protocol) {
case 'ssh':
case 'telnet':
case 'mysql':
case 'mariadb':
case 'postgresql':
case 'redis':
case 'oracle':
case 'sqlserver':
case 'mongodb':
case 'clickhouse':
case 'k8s':
this.connectMethod = {
component: 'koko',
type: 'web',
value: 'web_cli',
label: 'Web CLI',
endpoint_protocol: endpointProtocol,
disabled: false
};
return 'web_cli';
case 'http':
case 'https':
this.connectMethod = {
component: 'lion',
type: 'web',
value: 'chrome',
label: 'Chrome',
endpoint_protocol: endpointProtocol,
disabled: false
};
return 'chrome';
case 'rdp':
case 'vnc':
this.connectMethod = {
component: 'lion',
type: 'web',
value: 'web_gui',
label: 'Web GUI',
endpoint_protocol: endpointProtocol,
disabled: false
};
return 'web_gui';
case 'sftp':
this.connectMethod = {
component: 'koko',
type: 'web',
value: 'web_sftp',
label: 'Web SFTP',
endpoint_protocol: endpointProtocol,
disabled: false
};
return 'web_sftp';
default:
this.connectMethod = {
component: 'koko',
type: 'web',
value: 'web_cli',
label: 'Web CLI',
endpoint_protocol: endpointProtocol,
disabled: false
};
return 'web_cli';
}
}
onNewView(view?) {
if (this.isDirect && !view) {
// 直连模式创建视图
this.view = new View(
this.permedAsset,
{
...this.connectData,
permed_protocol: { name: this.protocol },
connectMethod: this.connectMethod
},
this.connectToken,
'node'
);
} else if (view) {
this.view = view;
this.view.active = true;
}
if (this.view) {
this._viewSrv.addView(this.view);
this._viewSrv.activeView(this.view);
if (!this.isDirect) {
this.startTimer();
}
// 发送视图变更消息
setTimeout(
() => {
this._drawerStateService.sendComponentMessage({
name: 'TAB_VIEW_CHANGE',
data: this.view.id
});
},
this.isDirect ? 100 : 500
);
}
}
/**
* 处理关闭连接
*/
public async handleCloseConnect() {
if (this.isDirect) {
if (window.confirm(`${this._i18n.instant('TurnOffReminders')}`)) {
this.stopTimer();
window.close();
}
} else {
this.stopTimer();
window.close();
}
}
/**
* 处理打开抽屉
*/
public async handleOpenDrawer() {
if (this.isDirect) {
this._http.adminConnectToken(this.permedAsset, this.connectData, false, false, '').subscribe(
resp => {
const fileManagerToken = resp ? resp.id : '';
this._drawerStateService.sendComponentMessage({
name: 'OPEN_SETTING',
data: {
direct: true,
fileManagerToken: fileManagerToken
}
});
return this._logger.info(`[Luna] Send OPEN_SETTING with fileManagerToken`);
},
error => {
const dialogRef = this._dialog.create({
nzContent: ElementACLDialogComponent,
nzData: {
asset: this.permedAsset,
connectData: { ...this.connectData, direct: true },
code: error.error.code,
tokenAction: 'create',
error: error
}
});
dialogRef.afterClose.subscribe(token => {
if (token) {
const fileManagerToken = token.id;
if (!fileManagerToken) {
alert(this._i18n.instant('VerificationFailed'));
return;
}
this._drawerStateService.sendComponentMessage({
name: 'OPEN_SETTING',
data: {
direct: true,
fileManagerToken: fileManagerToken
}
});
return;
}
alert(this._i18n.instant('VerificationFailed'));
});
}
);
} else {
this._drawerStateService.sendComponentMessage({
name: 'OPEN_SETTING',
data: {
direct: false
}
});
}
}
/**
* 处理页面可见性变化和计时器管理
*/
handleEventChangeTime() {
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
this.isActive = false;
this.stopTimer();
const currentTime = new Date().getTime();
this.pausedElapsedTime += currentTime - this.startTime.getTime();
} else {
setTimeout(() => {
this.isActive = true;
this.startTime = new Date();
this.startTimer();
}, 0);
}
});
document.addEventListener('mousemove', this.handleMouseMove.bind(this));
}
/**
* 处理鼠标移动事件,控制操作图标显示
*/
private handleMouseMove(event: MouseEvent): void {
this.showActionIcons = event.clientY <= 65;
}
/**
* 开始计时器
*/
private startTimer(): void {
if (this.timerInterval) {
this.stopTimer();
}
this.isTimerStopped = false;
this.timerInterval = setInterval(() => this.updateConnectTime(), 1000);
}
/**
* 停止计时器
*/
private stopTimer(): void {
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
this.isTimerStopped = true;
}
}
/**
* 补零
*/
private padZero(value: number): string {
return String(value).padStart(2, '0');
}
/**
* 更新连接时间
*/
private updateConnectTime(): void {
if (this.isTimerStopped) {
return;
}
const currentTime = new Date();
const elapsed = currentTime.getTime() - this.startTime.getTime() + this.pausedElapsedTime;
const hours = Math.floor((elapsed / (1000 * 60 * 60)) % 24);
const minutes = Math.floor((elapsed / (1000 * 60)) % 60);
const seconds = Math.floor((elapsed / 1000) % 60);
this.totalConnectTime = `${this.padZero(hours)}:${this.padZero(
minutes
)}:${this.padZero(seconds)}`;
}
/**
* 获取资产信息(用于显示)
*/
public getAssetInfo(): any {
if (this.isDirect) {
return {
name: this.assetName || 'Unknown Asset',
protocol: this.protocol || 'Unknown Protocol'
};
} else if (this.view && this.view.asset) {
return {
name: this.view.asset.name || 'Unknown Asset',
protocol: this.view.connectData?.protocol?.name || 'Unknown Protocol'
};
}
return {
name: 'Unknown Asset',
protocol: 'Unknown Protocol'
};
}
/**
* 判断是否为非协议连接
*/
public isNoneProtocol(): boolean {
if (this.isDirect) {
const protocols = [
'mysql',
'mariadb',
'postgresql',
'redis',
'oracle',
'sqlserver',
'mongodb',
'clickhouse',
'k8s',
'http',
'https'
];
return protocols.includes(this.protocol);
} else {
const assetInfo = this.getAssetInfo();
return ['k8s', 'website'].includes(assetInfo.protocol);
}
}
/**
* 判断当前视图是否为 GUI 组件
*/
public isGuiComponent(): boolean {
const componentName = this.view?.connectMethod?.component as string | undefined;
return !!componentName && this.guiComponents.has(componentName);
}
/**
* 判断当前视图是否为终端类组件
*/
public isTerminalComponent(): boolean {
const componentName = this.view?.connectMethod?.component as string | undefined;
return !!componentName && this.terminalComponents.has(componentName);
}
/**
* 是否为 Web SFTP
*/
public isWebSftp(): boolean {
return this.view?.connectMethod?.value === 'web_sftp';
}
/**
* 是否为 Web CLI 或 Web GUI
*/
public isWebCliOrGui(): boolean {
const value = this.view?.connectMethod?.value as string | undefined;
return (
value === 'web_cli' ||
value === 'web_gui' ||
value === 'db_guide' ||
value === 'vnc_guide'||
value === 'ssh_guide'
);
}
}