-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcreate-connection.use.case.ts
More file actions
140 lines (133 loc) · 6.42 KB
/
create-connection.use.case.ts
File metadata and controls
140 lines (133 loc) · 6.42 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
import { BadRequestException, Inject, Injectable, InternalServerErrorException, Scope } from '@nestjs/common';
import { getDataAccessObject } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/create-data-access-object.js';
import * as Sentry from '@sentry/node';
import AbstractUseCase from '../../../common/abstract-use.case.js';
import { IGlobalDatabaseContext } from '../../../common/application/global-database-context.interface.js';
import { BaseType } from '../../../common/data-injection.tokens.js';
import { Messages } from '../../../exceptions/text/messages.js';
import { Encryptor } from '../../../helpers/encryption/encryptor.js';
import { isConnectionTypeAgent, slackPostMessage } from '../../../helpers/index.js';
import { SharedJobsService } from '../../shared-jobs/shared-jobs.service.js';
import { UserRoleEnum } from '../../user/enums/user-role.enum.js';
import { UserEntity } from '../../user/user.entity.js';
import { CreateConnectionDs } from '../application/data-structures/create-connection.ds.js';
import { CreatedConnectionDTO } from '../application/dto/created-connection.dto.js';
import { ConnectionEntity } from '../connection.entity.js';
import { generateCedarPolicyForGroup } from '../../cedar-authorization/cedar-policy-generator.js';
import { AccessLevelEnum } from '../../../enums/index.js';
import { buildConnectionEntity } from '../utils/build-connection-entity.js';
import { buildCreatedConnectionDs } from '../utils/build-created-connection.ds.js';
import { processAWSConnection } from '../utils/process-aws-connection.util.js';
import { validateCreateConnectionData } from '../utils/validate-create-connection-data.js';
import { ICreateConnection } from './use-cases.interfaces.js';
@Injectable({ scope: Scope.REQUEST })
export class CreateConnectionUseCase
extends AbstractUseCase<CreateConnectionDs, CreatedConnectionDTO>
implements ICreateConnection
{
constructor(
@Inject(BaseType.GLOBAL_DB_CONTEXT)
protected _dbContext: IGlobalDatabaseContext,
private readonly sharedJobsService: SharedJobsService,
) {
super();
}
protected async implementation(createConnectionData: CreateConnectionDs): Promise<CreatedConnectionDTO> {
const {
creation_info: { authorId, masterPwd },
} = createConnectionData;
const connectionAuthor: UserEntity = await this._dbContext.userRepository.findOneUserById(authorId);
if (!connectionAuthor) {
throw new InternalServerErrorException(Messages.USER_NOT_FOUND);
}
if (connectionAuthor.role !== UserRoleEnum.ADMIN && connectionAuthor.role !== UserRoleEnum.DB_ADMIN) {
throw new BadRequestException(Messages.CANT_CREATE_CONNECTION_USER_NON_COMPANY_ADMIN);
}
await slackPostMessage(
Messages.USER_TRY_CREATE_CONNECTION(connectionAuthor.email, createConnectionData.connection_parameters.type),
);
await validateCreateConnectionData(createConnectionData);
createConnectionData = await processAWSConnection(createConnectionData);
let isConnectionTestedSuccessfully: boolean = false;
if (!isConnectionTypeAgent(createConnectionData.connection_parameters.type)) {
const connectionParamsCopy = {
...createConnectionData.connection_parameters,
};
const dao = getDataAccessObject(connectionParamsCopy);
try {
const testResult = await dao.testConnect();
isConnectionTestedSuccessfully = testResult.result;
} catch (e) {
const text: string = e.message.toLowerCase();
isConnectionTestedSuccessfully = false;
if (text.includes('ssl required') || text.includes('ssl connection required')) {
createConnectionData.connection_parameters.ssl = true;
connectionParamsCopy.ssl = true;
try {
const updatedDao = getDataAccessObject(connectionParamsCopy);
const sslTestResult = await updatedDao.testConnect();
isConnectionTestedSuccessfully = sslTestResult.result;
} catch (_e) {
isConnectionTestedSuccessfully = false;
createConnectionData.connection_parameters.ssl = false;
connectionParamsCopy.ssl = false;
}
}
}
}
let connectionCopy: ConnectionEntity = null;
try {
const createdConnection: ConnectionEntity = await buildConnectionEntity(createConnectionData, connectionAuthor);
const savedConnection: ConnectionEntity =
await this._dbContext.connectionRepository.saveNewConnection(createdConnection);
connectionCopy = { ...savedConnection } as ConnectionEntity;
if (savedConnection.masterEncryption && masterPwd && !isConnectionTypeAgent(savedConnection.type)) {
connectionCopy = Encryptor.decryptConnectionCredentials(connectionCopy, masterPwd);
}
let token: string;
if (isConnectionTypeAgent(savedConnection.type)) {
token = await this._dbContext.agentRepository.createNewAgentForConnectionAndReturnToken(savedConnection);
}
const createdAdminGroup = await this._dbContext.groupRepository.createdAdminGroupInConnection(
savedConnection,
connectionAuthor,
);
createdAdminGroup.cedarPolicy = generateCedarPolicyForGroup(
savedConnection.id,
true,
{
connection: { connectionId: savedConnection.id, accessLevel: AccessLevelEnum.edit },
group: { groupId: createdAdminGroup.id, accessLevel: AccessLevelEnum.edit },
tables: [],
},
);
await this._dbContext.groupRepository.saveNewOrUpdatedGroup(createdAdminGroup);
delete createdAdminGroup.connection;
await this._dbContext.userRepository.saveUserEntity(connectionAuthor);
createdConnection.groups = [createdAdminGroup];
const foundUserCompany = await this._dbContext.companyInfoRepository.findOneCompanyInfoByUserIdWithConnections(
connectionAuthor.id,
);
if (foundUserCompany) {
const connection = await this._dbContext.connectionRepository.findOne({
where: { id: savedConnection.id },
});
connection.company = foundUserCompany;
await this._dbContext.connectionRepository.saveUpdatedConnection(connection);
}
await slackPostMessage(
Messages.USER_CREATED_CONNECTION(connectionAuthor.email, createConnectionData.connection_parameters.type),
);
const connectionRO = buildCreatedConnectionDs(savedConnection, token, masterPwd);
return connectionRO;
} finally {
if (isConnectionTestedSuccessfully && !isConnectionTypeAgent(connectionCopy.type)) {
// Fire-and-forget: run AI scan in background without blocking response
this.sharedJobsService.scanDatabaseAndCreateSettingsAndWidgetsWithAI(connectionCopy).catch((error) => {
console.error('Background AI scan failed:', error);
Sentry.captureException(error);
});
}
}
}
}