Skip to content

Commit

Permalink
Merge pull request #758 from rocket-admin/backend_refactoring
Browse files Browse the repository at this point in the history
Backend refactoring
  • Loading branch information
Artuomka authored Jul 29, 2024
2 parents f829f00 + dcbe596 commit 76f9c09
Show file tree
Hide file tree
Showing 36 changed files with 199 additions and 147 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import {
FoundUserEmailCompaniesInfoDs,
FoundUserFullCompanyInfoDs,
} from './application/data-structures/found-company-info.ds.js';
import { SimpleFoundUserInfoDs } from '../user/application/data-structures/found-user.ds.js';
import { SimpleFoundUserInfoDs } from '../user/dto/found-user.dto.js';
import { SuccessResponse } from '../../microservices/saas-microservice/data-structures/common-responce.ds.js';
import { RevokeInvitationRequestDto } from './application/dto/revoke-invitation-request.dto.js';
import { UpdateCompanyNameDto } from './application/dto/update-company-name.dto.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { InTransactionEnum } from '../../../enums/in-transaction.enum.js';
import { SuccessResponse } from '../../../microservices/saas-microservice/data-structures/common-responce.ds.js';
import { SimpleFoundUserInfoDs } from '../../user/application/data-structures/found-user.ds.js';
import { SimpleFoundUserInfoDs } from '../../user/dto/found-user.dto.js';
import { IToken } from '../../user/utils/generate-gwt-token.js';
import { AcceptUserValidationInCompany } from '../application/data-structures/accept-user-invitation-in-company.ds.js';
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ 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 { IGetUsersInCompany } from './company-info-use-cases.interface.js';
import { SimpleFoundUserInfoDs } from '../../user/application/data-structures/found-user.ds.js';
import { SimpleFoundUserInfoDs } from '../../user/dto/found-user.dto.js';
import { Messages } from '../../../exceptions/text/messages.js';
import { buildSimpleUserInfoDs } from '../../user/utils/build-created-user.ds.js';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AccessLevelEnum } from '../../../../enums/index.js';
import { ConnectionTypesEnum } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/enums/connection-types-enum.js';
import { UserEntity } from '../../../user/user.entity.js';
import { FoundGroupDataWithUsersDs } from '../../../group/application/data-sctructures/found-user-groups.ds.js';
import { SimpleFoundUserInfoDs } from '../../../user/application/data-structures/found-user.ds.js';
import { SimpleFoundUserInfoDs } from '../../../user/dto/found-user.dto.js';

export class FoundDirectConnectionsDs {
@ApiProperty()
Expand Down Expand Up @@ -71,6 +71,9 @@ export class FoundDirectConnectionsDs {

@ApiProperty({ required: false })
authSource?: string;

@ApiProperty()
isTestConnection: boolean;
}

export class FoundDirectConnectionsNonePermissionDs {
Expand All @@ -85,6 +88,9 @@ export class FoundDirectConnectionsNonePermissionDs {

@ApiProperty()
database: string;

@ApiProperty()
isTestConnection: boolean;
}

export class FoundAgentConnectionsDs {
Expand All @@ -105,6 +111,9 @@ export class FoundAgentConnectionsDs {

@ApiProperty()
signing_key: string;

@ApiProperty()
isTestConnection: boolean;
}

export class FoundDirectConnectionsWithGroupAndUsersDs extends FoundDirectConnectionsDs {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { ConnectionTypesEnum } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/enums/connection-types-enum.js';
import { FoundUserDs } from '../../../user/application/data-structures/found-user.ds.js';
import { FoundUserDto } from '../../../user/dto/found-user.dto.js';

export class CreatedGroupInConnectionDTO {
@ApiProperty()
Expand All @@ -12,8 +12,8 @@ export class CreatedGroupInConnectionDTO {
@ApiProperty()
isMain: boolean;

@ApiProperty({ isArray: true, type: FoundUserDs })
users: Array<FoundUserDs>;
@ApiProperty({ isArray: true, type: FoundUserDto })
users: Array<FoundUserDto>;
}

export class CreatedConnectionDTO {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ApiProperty } from '@nestjs/swagger';
import { AccessLevelEnum } from '../../../../enums/access-level.enum.js';
import { SimpleFoundUserInfoDs } from '../../../user/dto/found-user.dto.js';

export class FoundGroupInConnectionDTO {
@ApiProperty()
id: string;

@ApiProperty()
title: string;

@ApiProperty()
isMain: boolean;

@ApiProperty({ required: false, isArray: true, type: SimpleFoundUserInfoDs })
users?: Array<SimpleFoundUserInfoDs>;
}

export class FoundUserGroupsInConnectionDTO {
@ApiProperty({ type: FoundGroupInConnectionDTO })
group: FoundGroupInConnectionDTO;

@ApiProperty({ enum: AccessLevelEnum })
accessLevel: AccessLevelEnum;
}
18 changes: 8 additions & 10 deletions backend/src/entities/connection/connection.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,16 @@ import {
} from '../../helpers/index.js';
import { SentryInterceptor } from '../../interceptors/index.js';
import { AmplitudeService } from '../amplitude/amplitude.service.js';
import { GroupEntity } from '../group/group.entity.js';
import { IComplexPermission } from '../permission/permission.interface.js';
import { FindUserDs } from '../user/application/data-structures/find-user.ds.js';
import { FoundUserDs } from '../user/application/data-structures/found-user.ds.js';
import { FoundUserDto } from '../user/dto/found-user.dto.js';
import { CreateConnectionDs } from './application/data-structures/create-connection.ds.js';
import { CreateGroupInConnectionDs } from './application/data-structures/create-group-in-connection.ds.js';
import { CreatedConnectionDTO } from './application/dto/created-connection.dto.js';
import { DeleteConnectionDs } from './application/data-structures/delete-connection.ds.js';
import { DeleteGroupInConnectionDs } from './application/data-structures/delete-group-in-connection.ds.js';
import { FindOneConnectionDs } from './application/data-structures/find-one-connection.ds.js';
import { FoundConnectionsDs } from './application/data-structures/found-connections.ds.js';
import { FoundUserGroupsInConnectionDs } from './application/data-structures/found-user-groups-in-connection.ds.js';
import { GetGroupsInConnectionDs } from './application/data-structures/get-groups-in-connection.ds.js';
import { GetPermissionsInConnectionDs } from './application/data-structures/get-permissions-in-connection.ds.js';
import { RestoredConnectionDs } from './application/data-structures/restored-connection.ds.js';
Expand Down Expand Up @@ -70,14 +68,14 @@ import { CreateConnectionDto } from './application/dto/index.js';
import { UpdatedConnectionResponseDTO } from './application/dto/updated-connection-responce.dto.js';
import { DeleteConnectionReasonDto } from './application/dto/delete-connection.dto.js';
import { DeleteGroupFromConnectionDTO } from './application/dto/delete-group-from-connection-request.dto.js';
import { CreateDeleteGroupInConnectionResponseDTO } from './application/dto/delete-froup-from-connection-response.dto.js';
import { CreateGroupInConnectionDTO } from './application/dto/create-group-in-connection.dto.js';
import { FoundPermissionsInConnectionDs } from './application/data-structures/found-permissions-in-connection.ds.js';
import { TestConnectionResponseDTO } from './application/dto/test-connection-response.dto.js';
import { ConnectionTokenResponseDTO } from './application/dto/new-connection-token-response.dto.js';
import { UpdateMasterPasswordRequestBodyDto } from './application/dto/update-master-password-request-body.dto.js';
import { FoundOneConnectionDs } from './application/data-structures/found-one-connection.ds.js';
import { FoundGroupResponseDto } from '../group/dto/found-group-response.dto.js';
import { FoundUserGroupsInConnectionDTO } from './application/dto/found-user-groups-in-connection.dto.js';

@UseInterceptors(SentryInterceptor)
@Controller()
Expand Down Expand Up @@ -141,14 +139,14 @@ export class ConnectionController {
@ApiOperation({ summary: 'Get all users in connection' })
@ApiResponse({
status: 200,
type: Array<FoundUserDs>,
type: Array<FoundUserDto>,
})
@UseGuards(ConnectionReadGuard)
@Get('/connection/users/:connectionId')
async findAllUsers(
@UserId() userId: string,
@SlugUuid('connectionId') connectionId: string,
): Promise<Array<FoundUserDs>> {
): Promise<Array<FoundUserDto>> {
try {
return await this.findAllUsersInConnectionUseCase.execute(connectionId, InTransactionEnum.OFF);
} catch (e) {
Expand Down Expand Up @@ -372,15 +370,15 @@ export class ConnectionController {
@ApiResponse({
status: 201,
description: 'Group was created.',
type: CreateDeleteGroupInConnectionResponseDTO,
type: FoundGroupResponseDto,
})
@UseGuards(ConnectionEditGuard)
@Post('/connection/group/:connectionId')
async createGroupInConnection(
@Body() groupData: CreateGroupInConnectionDTO,
@SlugUuid('connectionId') connectionId: string,
@UserId() userId: string,
): Promise<Omit<GroupEntity, 'connection'>> {
): Promise<FoundGroupResponseDto> {
const { title } = groupData;
if (!title) {
throw new BadRequestException(Messages.GROUP_TITLE_MISSING);
Expand All @@ -400,14 +398,14 @@ export class ConnectionController {
@ApiOperation({ summary: 'Get all groups in connection' })
@ApiResponse({
status: 200,
type: FoundUserGroupsInConnectionDs,
type: FoundUserGroupsInConnectionDTO,
isArray: true,
})
@Get('/connection/groups/:connectionId')
async getGroupsInConnection(
@UserId() userId: string,
@SlugUuid('connectionId') connectionId: string,
): Promise<Array<FoundUserGroupsInConnectionDs>> {
): Promise<Array<FoundUserGroupsInConnectionDTO>> {
if (!connectionId) {
throw new BadRequestException(Messages.ID_MISSING);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ 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 { GroupEntity } from '../../group/group.entity.js';
import { CreateGroupInConnectionDs } from '../application/data-structures/create-group-in-connection.ds.js';
import { buildNewGroupEntityForConnectionWithUser } from '../utils/build-new-group-entity-for-connection-with-user.js';
import { ICreateGroupInConnection } from './use-cases.interfaces.js';
import { buildFoundGroupResponseDto } from '../../group/utils/biuld-found-group-response.dto.js';
import { FoundGroupResponseDto } from '../../group/dto/found-group-response.dto.js';

@Injectable({ scope: Scope.REQUEST })
export class CreateGroupInConnectionUseCase
extends AbstractUseCase<CreateGroupInConnectionDs, Omit<GroupEntity, 'connection' | 'users' | 'permissions'>>
extends AbstractUseCase<CreateGroupInConnectionDs, FoundGroupResponseDto>
implements ICreateGroupInConnection
{
constructor(
Expand All @@ -20,7 +21,7 @@ export class CreateGroupInConnectionUseCase
super();
}

protected async implementation(inputData: CreateGroupInConnectionDs): Promise<Omit<GroupEntity, 'connection'>> {
protected async implementation(inputData: CreateGroupInConnectionDs): Promise<FoundGroupResponseDto> {
const {
group_parameters: { connectionId, title },
creation_info: { cognitoUserName },
Expand All @@ -32,7 +33,6 @@ export class CreateGroupInConnectionUseCase
const foundUser = await this._dbContext.userRepository.findOneUserById(cognitoUserName);
const newGroupEntity = buildNewGroupEntityForConnectionWithUser(connectionToUpdate, foundUser, title);
const savedGroup = await this._dbContext.groupRepository.saveNewOrUpdatedGroup(newGroupEntity);
delete savedGroup.connection;
return savedGroup;
return buildFoundGroupResponseDto(savedGroup);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { Messages } from '../../../exceptions/text/messages.js';
import { ConnectionEntity } from '../connection.entity.js';
import { buildFoundConnectionDs } from '../utils/build-found-connection.ds.js';

export type RequiredConnectionKeys = Pick<ConnectionEntity, 'id' | 'database'>;
export type RequiredConnectionKeys = Pick<ConnectionEntity, 'id' | 'database' | 'isTestConnection'>;
export type OptionalConnectionKeys = Partial<Omit<ConnectionEntity, keyof RequiredConnectionKeys>>;
export type FilteredConnection = RequiredConnectionKeys & OptionalConnectionKeys;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { Inject, Injectable } from '@nestjs/common';
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 { FoundUserDs } from '../../user/application/data-structures/found-user.ds.js';
import { FoundUserDto } from '../../user/dto/found-user.dto.js';
import { IFindUsersInConnection } from './use-cases.interfaces.js';
import { buildFoundUserDto } from '../../user/utils/build-found-user.dto.js';
import { UserEntity } from '../../user/user.entity.js';

@Injectable()
export class FindAllUsersInConnectionUseCase
extends AbstractUseCase<string, Array<FoundUserDs>>
extends AbstractUseCase<string, Array<FoundUserDto>>
implements IFindUsersInConnection
{
constructor(
Expand All @@ -17,20 +19,11 @@ export class FindAllUsersInConnectionUseCase
super();
}

protected async implementation(connectionId: string): Promise<Array<FoundUserDs>> {
protected async implementation(connectionId: string): Promise<Array<FoundUserDto>> {
const userInConnection = await this._dbContext.userRepository.findAllUsersInConnection(connectionId);
return userInConnection.map((user) => {
return {
id: user.id,
isActive: user.isActive,
email: user.email,
createdAt: user.createdAt,
name: user.name,
suspended: user.suspended,
role: user.role,
is_2fa_enabled: user.otpSecretKey !== null && user.isOTPEnabled,
externalRegistrationProvider: user.externalRegistrationProvider,
};
//todo fix type after repository types are fixed
return buildFoundUserDto(user as UserEntity);
});
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpStatus, Inject, Injectable } from '@nestjs/common';
import { BadRequestException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { HttpException } from '@nestjs/common/exceptions/http.exception.js';
import AbstractUseCase from '../../../common/abstract-use.case.js';
import { IGlobalDatabaseContext } from '../../../common/application/global-database-context.interface.js';
Expand All @@ -13,6 +13,8 @@ import { FindOneConnectionDs } from '../application/data-structures/find-one-con
import { IFindOneConnection } from './use-cases.interfaces.js';
import { FoundOneConnectionDs } from '../application/data-structures/found-one-connection.ds.js';
import { buildFoundConnectionDs } from '../utils/build-found-connection.ds.js';
import { ConnectionEntity } from '../connection.entity.js';
import { FilteredConnection } from './find-all-connections.use.case.js';

@Injectable()
export class FindOneConnectionUseCase
Expand All @@ -27,14 +29,9 @@ export class FindOneConnectionUseCase
}

protected async implementation(inputData: FindOneConnectionDs): Promise<FoundOneConnectionDs> {
let connection = await this._dbContext.connectionRepository.findOneConnection(inputData.connectionId);
const connection = await this._dbContext.connectionRepository.findOneConnection(inputData.connectionId);
if (!connection) {
throw new HttpException(
{
message: Messages.CONNECTION_NOT_FOUND,
},
HttpStatus.BAD_REQUEST,
);
throw new BadRequestException(Messages.CONNECTION_NOT_FOUND);
}
const accessLevel: AccessLevelEnum = await this._dbContext.userAccessRepository.getUserConnectionAccessLevel(
inputData.cognitoUserName,
Expand All @@ -51,21 +48,28 @@ export class FindOneConnectionUseCase
);
}

if (accessLevel === AccessLevelEnum.none) {
for (const key in connection) {
if (!Constants.CONNECTION_KEYS_NONE_PERMISSION.includes(key)) {
const filterConnectionKeys = (connection: ConnectionEntity, allowedKeys: Array<string>): FilteredConnection => {
return Object.keys(connection).reduce((acc, key) => {
if (allowedKeys.includes(key)) {
// eslint-disable-next-line security/detect-object-injection
delete connection[key];
acc[key] = connection[key];
}
}
}
if (accessLevel !== AccessLevelEnum.edit) {
delete connection.signing_key;
return acc;
}, {} as FilteredConnection);
};
let filteredConnection: FilteredConnection = connection;

if (accessLevel === AccessLevelEnum.none) {
filteredConnection = filterConnectionKeys(connection, Constants.CONNECTION_KEYS_NONE_PERMISSION);
} else if (accessLevel !== AccessLevelEnum.edit) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { signing_key, ...rest } = connection;
filteredConnection = rest;
}

if (connection.masterEncryption && inputData.masterPwd && accessLevel !== AccessLevelEnum.none) {
if (filteredConnection.masterEncryption && inputData.masterPwd && accessLevel !== AccessLevelEnum.none) {
try {
connection = Encryptor.decryptConnectionCredentials(connection, inputData.masterPwd);
filteredConnection = Encryptor.decryptConnectionCredentials(connection, inputData.masterPwd);
} catch (e) {
console.log('-> Error decrypting connection credentials', e);
throw new HttpException(
Expand All @@ -86,7 +90,7 @@ export class FindOneConnectionUseCase
? buildFoundConnectionPropertiesDs(connection.connection_properties)
: null;
return {
connection: buildFoundConnectionDs(connection),
connection: buildFoundConnectionDs(filteredConnection),
accessLevel: accessLevel,
groupManagement: groupManagement,
connectionProperties: connectionProperties,
Expand Down
Loading

0 comments on commit 76f9c09

Please sign in to comment.