mirror of
https://gitlab.com/mobicoop/v3/service/auth.git
synced 2026-01-02 20:52:41 +00:00
crate/update/validate auth
This commit is contained in:
@@ -1,22 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
import { classes } from '@automapper/classes';
|
||||
import { AutomapperModule } from '@automapper/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
AutomapperModule.forRoot({ strategyInitializer: classes() }),
|
||||
AuthModule,
|
||||
],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
20
src/main.ts
20
src/main.ts
@@ -1,8 +1,24 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
|
||||
import { join } from 'path';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(3000);
|
||||
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
|
||||
AppModule,
|
||||
{
|
||||
transport: Transport.GRPC,
|
||||
options: {
|
||||
package: 'auth',
|
||||
protoPath: join(
|
||||
__dirname,
|
||||
'modules/auth/adapters/primaries/auth.proto',
|
||||
),
|
||||
url: process.env.SERVICE_URL + ':' + process.env.SERVICE_PORT,
|
||||
loader: { keepCase: true },
|
||||
},
|
||||
},
|
||||
);
|
||||
await app.listen();
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
70
src/modules/auth/adapters/primaries/auth.controller.ts
Normal file
70
src/modules/auth/adapters/primaries/auth.controller.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Mapper } from '@automapper/core';
|
||||
import { InjectMapper } from '@automapper/nestjs';
|
||||
import { Controller } from '@nestjs/common';
|
||||
import { CommandBus, QueryBus } from '@nestjs/cqrs';
|
||||
import { GrpcMethod, RpcException } from '@nestjs/microservices';
|
||||
import { DatabaseException } from 'src/modules/database/src/exceptions/DatabaseException';
|
||||
import { CreateAuthCommand } from '../../commands/create-auth.command';
|
||||
import { UpdateAuthCommand } from '../../commands/update-auth.command';
|
||||
import { CreateAuthRequest } from '../../domain/dto/create-auth.request';
|
||||
import { UpdateAuthRequest } from '../../domain/dto/update-auth.request';
|
||||
import { ValidateAuthRequest } from '../../domain/dto/validate-auth.request';
|
||||
import { Auth } from '../../domain/entities/auth';
|
||||
import { ValidateQuery } from '../../queries/validate.query';
|
||||
import { AuthPresenter } from './auth.presenter';
|
||||
|
||||
@Controller()
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly _commandBus: CommandBus,
|
||||
private readonly _queryBus: QueryBus,
|
||||
@InjectMapper() private readonly _mapper: Mapper,
|
||||
) {}
|
||||
|
||||
@GrpcMethod('AuthService', 'Validate')
|
||||
async validate(data: ValidateAuthRequest): Promise<AuthPresenter> {
|
||||
try {
|
||||
const auth = await this._queryBus.execute(
|
||||
new ValidateQuery(data.username, data.password),
|
||||
);
|
||||
return this._mapper.map(auth, Auth, AuthPresenter);
|
||||
} catch (e) {
|
||||
throw new RpcException({
|
||||
code: 7,
|
||||
message: 'Permission denied',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@GrpcMethod('AuthService', 'Create')
|
||||
async createUser(data: CreateAuthRequest): Promise<AuthPresenter> {
|
||||
try {
|
||||
const auth = await this._commandBus.execute(new CreateAuthCommand(data));
|
||||
return this._mapper.map(auth, Auth, AuthPresenter);
|
||||
} catch (e) {
|
||||
if (e instanceof DatabaseException) {
|
||||
if (e.message.includes('Already exists')) {
|
||||
throw new RpcException({
|
||||
code: 6,
|
||||
message: 'Auth already exists',
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new RpcException({});
|
||||
}
|
||||
}
|
||||
|
||||
@GrpcMethod('AuthService', 'Update')
|
||||
async updateAuth(data: UpdateAuthRequest): Promise<AuthPresenter> {
|
||||
try {
|
||||
const auth = await this._commandBus.execute(new UpdateAuthCommand(data));
|
||||
|
||||
return this._mapper.map(auth, Auth, AuthPresenter);
|
||||
} catch (e) {
|
||||
throw new RpcException({
|
||||
code: 7,
|
||||
message: 'Permission denied',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
9
src/modules/auth/adapters/primaries/auth.presenter.ts
Normal file
9
src/modules/auth/adapters/primaries/auth.presenter.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
|
||||
export class AuthPresenter {
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
|
||||
@AutoMap()
|
||||
username: string;
|
||||
}
|
||||
32
src/modules/auth/adapters/primaries/auth.proto
Normal file
32
src/modules/auth/adapters/primaries/auth.proto
Normal file
@@ -0,0 +1,32 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package auth;
|
||||
|
||||
service AuthService {
|
||||
rpc Validate(AuthByUsernamePassword) returns (AuthByUuid);
|
||||
rpc Create(AuthWithPassword) returns (Auth);
|
||||
rpc Update(AuthWithPassword) returns (Auth);
|
||||
rpc Delete(AuthByUuid) returns (Empty);
|
||||
}
|
||||
|
||||
message AuthByUsernamePassword {
|
||||
string username = 1;
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
message AuthWithPassword {
|
||||
string uuid = 1;
|
||||
string username = 2;
|
||||
string password = 3;
|
||||
}
|
||||
|
||||
message AuthByUuid {
|
||||
string uuid = 1;
|
||||
}
|
||||
|
||||
message Auth {
|
||||
string uuid = 1;
|
||||
string username = 2;
|
||||
}
|
||||
|
||||
message Empty {}
|
||||
8
src/modules/auth/adapters/secondaries/auth.repository.ts
Normal file
8
src/modules/auth/adapters/secondaries/auth.repository.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthNZRepository } from '../../../database/src/domain/authnz-repository';
|
||||
import { Auth } from '../../domain/entities/auth';
|
||||
|
||||
@Injectable()
|
||||
export class AuthRepository extends AuthNZRepository<Auth> {
|
||||
protected _model = 'auth';
|
||||
}
|
||||
23
src/modules/auth/auth.module.ts
Normal file
23
src/modules/auth/auth.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { AuthController } from './adapters/primaries/auth.controller';
|
||||
import { CreateAuthUseCase } from './domain/usecases/create-auth.usecase';
|
||||
import { ValidateUseCase } from './domain/usecases/validate-auth.usecase';
|
||||
import { AuthProfile } from './mappers/auth.profile';
|
||||
import { AuthRepository } from './adapters/secondaries/auth.repository';
|
||||
import { UpdateAuthUseCase } from './domain/usecases/update-auth.usecase';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, CqrsModule],
|
||||
controllers: [AuthController],
|
||||
providers: [
|
||||
AuthProfile,
|
||||
AuthRepository,
|
||||
ValidateUseCase,
|
||||
CreateAuthUseCase,
|
||||
UpdateAuthUseCase,
|
||||
],
|
||||
exports: [],
|
||||
})
|
||||
export class AuthModule {}
|
||||
9
src/modules/auth/commands/create-auth.command.ts
Normal file
9
src/modules/auth/commands/create-auth.command.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { CreateAuthRequest } from '../domain/dto/create-auth.request';
|
||||
|
||||
export class CreateAuthCommand {
|
||||
readonly createAuthRequest: CreateAuthRequest;
|
||||
|
||||
constructor(request: CreateAuthRequest) {
|
||||
this.createAuthRequest = request;
|
||||
}
|
||||
}
|
||||
9
src/modules/auth/commands/update-auth.command.ts
Normal file
9
src/modules/auth/commands/update-auth.command.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { UpdateAuthRequest } from '../domain/dto/update-auth.request';
|
||||
|
||||
export class UpdateAuthCommand {
|
||||
readonly updateAuthRequest: UpdateAuthRequest;
|
||||
|
||||
constructor(request: UpdateAuthRequest) {
|
||||
this.updateAuthRequest = request;
|
||||
}
|
||||
}
|
||||
18
src/modules/auth/domain/dto/create-auth.request.ts
Normal file
18
src/modules/auth/domain/dto/create-auth.request.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class CreateAuthRequest {
|
||||
@IsString()
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@AutoMap()
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@AutoMap()
|
||||
password: string;
|
||||
}
|
||||
16
src/modules/auth/domain/dto/update-auth.request.ts
Normal file
16
src/modules/auth/domain/dto/update-auth.request.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
import { IsString } from 'class-validator';
|
||||
|
||||
export class UpdateAuthRequest {
|
||||
@IsString()
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
|
||||
@IsString()
|
||||
@AutoMap()
|
||||
username?: string;
|
||||
|
||||
@IsString()
|
||||
@AutoMap()
|
||||
password?: string;
|
||||
}
|
||||
11
src/modules/auth/domain/dto/validate-auth.request.ts
Normal file
11
src/modules/auth/domain/dto/validate-auth.request.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ValidateAuthRequest {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
}
|
||||
12
src/modules/auth/domain/entities/auth.ts
Normal file
12
src/modules/auth/domain/entities/auth.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
|
||||
export class Auth {
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
|
||||
@AutoMap()
|
||||
username: string;
|
||||
|
||||
@AutoMap()
|
||||
password: string;
|
||||
}
|
||||
20
src/modules/auth/domain/usecases/create-auth.usecase.ts
Normal file
20
src/modules/auth/domain/usecases/create-auth.usecase.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
|
||||
import { CreateAuthCommand } from '../../commands/create-auth.command';
|
||||
import { Auth } from '../entities/auth';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
@CommandHandler(CreateAuthCommand)
|
||||
export class CreateAuthUseCase {
|
||||
constructor(private readonly _repository: AuthRepository) {}
|
||||
|
||||
async execute(command: CreateAuthCommand): Promise<Auth> {
|
||||
const { password, ...authWithoutPassword } = command.createAuthRequest;
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
|
||||
return this._repository.create({
|
||||
password: hash,
|
||||
...authWithoutPassword,
|
||||
});
|
||||
}
|
||||
}
|
||||
29
src/modules/auth/domain/usecases/update-auth.usecase.ts
Normal file
29
src/modules/auth/domain/usecases/update-auth.usecase.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Mapper } from '@automapper/core';
|
||||
import { InjectMapper } from '@automapper/nestjs';
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
|
||||
import { UpdateAuthCommand } from '../../commands/update-auth.command';
|
||||
import { Auth } from '../entities/auth';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
@CommandHandler(UpdateAuthCommand)
|
||||
export class UpdateAuthUseCase {
|
||||
constructor(
|
||||
private readonly _repository: AuthRepository,
|
||||
@InjectMapper() private readonly _mapper: Mapper,
|
||||
) {}
|
||||
|
||||
async execute(command: UpdateAuthCommand): Promise<Auth> {
|
||||
const { uuid, username, password } = command.updateAuthRequest;
|
||||
const request = {};
|
||||
if (username) {
|
||||
request['username'] = username;
|
||||
}
|
||||
if (password) {
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
request['password'] = hash;
|
||||
}
|
||||
|
||||
return this._repository.update(uuid, request);
|
||||
}
|
||||
}
|
||||
23
src/modules/auth/domain/usecases/validate-auth.usecase.ts
Normal file
23
src/modules/auth/domain/usecases/validate-auth.usecase.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { QueryHandler } from '@nestjs/cqrs';
|
||||
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
|
||||
import { ValidateQuery } from '../../queries/validate.query';
|
||||
import { Auth } from '../entities/auth';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { NotFoundException, UnauthorizedException } from '@nestjs/common';
|
||||
|
||||
@QueryHandler(ValidateQuery)
|
||||
export class ValidateUseCase {
|
||||
constructor(private readonly _authRepository: AuthRepository) {}
|
||||
|
||||
async execute(validate: ValidateQuery): Promise<Auth> {
|
||||
const auth = await this._authRepository.findOne({
|
||||
username: validate.username,
|
||||
});
|
||||
if (auth) {
|
||||
const isMatch = await bcrypt.compare(validate.password, auth.password);
|
||||
if (isMatch) return auth;
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
throw new NotFoundException();
|
||||
}
|
||||
}
|
||||
18
src/modules/auth/mappers/auth.profile.ts
Normal file
18
src/modules/auth/mappers/auth.profile.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { createMap, Mapper } from '@automapper/core';
|
||||
import { AutomapperProfile, InjectMapper } from '@automapper/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthPresenter } from '../adapters/primaries/auth.presenter';
|
||||
import { Auth } from '../domain/entities/auth';
|
||||
|
||||
@Injectable()
|
||||
export class AuthProfile extends AutomapperProfile {
|
||||
constructor(@InjectMapper() mapper: Mapper) {
|
||||
super(mapper);
|
||||
}
|
||||
|
||||
override get profile() {
|
||||
return (mapper) => {
|
||||
createMap(mapper, Auth, AuthPresenter);
|
||||
};
|
||||
}
|
||||
}
|
||||
9
src/modules/auth/queries/validate.query.ts
Normal file
9
src/modules/auth/queries/validate.query.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export class ValidateQuery {
|
||||
readonly username: string;
|
||||
readonly password: string;
|
||||
|
||||
constructor(username: string, password: string) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
61
src/modules/auth/tests/unit/create-auth.usecase.spec.ts
Normal file
61
src/modules/auth/tests/unit/create-auth.usecase.spec.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { classes } from '@automapper/classes';
|
||||
import { AutomapperModule } from '@automapper/nestjs';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
|
||||
import { CreateAuthCommand } from '../../commands/create-auth.command';
|
||||
import { CreateAuthRequest } from '../../domain/dto/create-auth.request';
|
||||
import { Auth } from '../../domain/entities/auth';
|
||||
import { CreateAuthUseCase } from '../../domain/usecases/create-auth.usecase';
|
||||
import { AuthProfile } from '../../mappers/auth.profile';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
const newAuthRequest: CreateAuthRequest = {
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
username: 'john.doe@email.com',
|
||||
password: 'John123',
|
||||
};
|
||||
const newAuthCommand: CreateAuthCommand = new CreateAuthCommand(newAuthRequest);
|
||||
|
||||
const mockAuthRepository = {
|
||||
create: jest.fn().mockResolvedValue({
|
||||
uuid: newAuthRequest.uuid,
|
||||
username: newAuthRequest.username,
|
||||
password: bcrypt.hashSync(newAuthRequest.password, 10),
|
||||
}),
|
||||
};
|
||||
|
||||
describe('CreateAuthUseCase', () => {
|
||||
let createAuthUseCase: CreateAuthUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
|
||||
providers: [
|
||||
{
|
||||
provide: AuthRepository,
|
||||
useValue: mockAuthRepository,
|
||||
},
|
||||
CreateAuthUseCase,
|
||||
AuthProfile,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
createAuthUseCase = module.get<CreateAuthUseCase>(CreateAuthUseCase);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(createAuthUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should create an auth and returns new entity object', async () => {
|
||||
const newAuth: Auth = await createAuthUseCase.execute(newAuthCommand);
|
||||
|
||||
expect(newAuth.username).toBe(newAuthRequest.username);
|
||||
|
||||
expect(
|
||||
bcrypt.compareSync(newAuthRequest.password, newAuth.password),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
119
src/modules/auth/tests/unit/update-auth.usecase.spec.ts
Normal file
119
src/modules/auth/tests/unit/update-auth.usecase.spec.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { classes } from '@automapper/classes';
|
||||
import { AutomapperModule } from '@automapper/nestjs';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UpdateAuthCommand } from '../../commands/update-auth.command';
|
||||
import { UpdateAuthRequest } from '../../domain/dto/update-auth.request';
|
||||
import { Auth } from '../../domain/entities/auth';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { UpdateAuthUseCase } from '../../domain/usecases/update-auth.usecase';
|
||||
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
|
||||
import { AuthProfile } from '../../mappers/auth.profile';
|
||||
|
||||
const originalAuth: Auth = new Auth();
|
||||
originalAuth.uuid = 'bb281075-1b98-4456-89d6-c643d3044a91';
|
||||
originalAuth.username = 'john.doe@email.com';
|
||||
originalAuth.password = 'encrypted_password';
|
||||
|
||||
const updateUsernameAuthRequest: UpdateAuthRequest = {
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
username: 'johnny.doe@email.com',
|
||||
};
|
||||
|
||||
const updatePasswordAuthRequest: UpdateAuthRequest = {
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
password: 'John1234',
|
||||
};
|
||||
|
||||
const updateAuthRequest: UpdateAuthRequest = {
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
username: 'johnny.doe@email.com',
|
||||
password: 'John1234',
|
||||
};
|
||||
|
||||
const updateUsernameAuthCommand: UpdateAuthCommand = new UpdateAuthCommand(
|
||||
updateUsernameAuthRequest,
|
||||
);
|
||||
|
||||
const updatePasswordAuthCommand: UpdateAuthCommand = new UpdateAuthCommand(
|
||||
updatePasswordAuthRequest,
|
||||
);
|
||||
|
||||
const updateAuthCommand: UpdateAuthCommand = new UpdateAuthCommand(
|
||||
updateAuthRequest,
|
||||
);
|
||||
|
||||
const mockAuthRepository = {
|
||||
update: jest.fn().mockImplementation((uuid: string, params: any) => {
|
||||
if (params.username && params.password) {
|
||||
const auth: Auth = { ...originalAuth };
|
||||
auth.username = params.username;
|
||||
auth.password = params.password;
|
||||
return Promise.resolve(auth);
|
||||
}
|
||||
if (params.username) {
|
||||
const auth: Auth = { ...originalAuth };
|
||||
auth.username = params.username;
|
||||
return Promise.resolve(auth);
|
||||
}
|
||||
if (params.password) {
|
||||
const auth: Auth = { ...originalAuth };
|
||||
auth.password = params.password;
|
||||
return Promise.resolve(auth);
|
||||
}
|
||||
}),
|
||||
};
|
||||
|
||||
describe('UpdateAuthUseCase', () => {
|
||||
let updateAuthUseCase: UpdateAuthUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
|
||||
|
||||
providers: [
|
||||
{
|
||||
provide: AuthRepository,
|
||||
useValue: mockAuthRepository,
|
||||
},
|
||||
UpdateAuthUseCase,
|
||||
AuthProfile,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
updateAuthUseCase = module.get<UpdateAuthUseCase>(UpdateAuthUseCase);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(updateAuthUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should update the username of an Auth', async () => {
|
||||
const updatedAuth: Auth = await updateAuthUseCase.execute(
|
||||
updateUsernameAuthCommand,
|
||||
);
|
||||
|
||||
expect(updatedAuth.username).toBe(updateUsernameAuthRequest.username);
|
||||
});
|
||||
it('should update the password of an Auth', async () => {
|
||||
const updatedAuth: Auth = await updateAuthUseCase.execute(
|
||||
updatePasswordAuthCommand,
|
||||
);
|
||||
expect(
|
||||
bcrypt.compareSync(
|
||||
updatePasswordAuthRequest.password,
|
||||
updatedAuth.password,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
it('should update the username and the password of an Auth', async () => {
|
||||
const updatedAuth: Auth = await updateAuthUseCase.execute(
|
||||
updateAuthCommand,
|
||||
);
|
||||
expect(updatedAuth.username).toBe(updateAuthRequest.username);
|
||||
expect(
|
||||
bcrypt.compareSync(updateAuthRequest.password, updatedAuth.password),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
9
src/modules/database/database.module.ts
Normal file
9
src/modules/database/database.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthRepository } from '../auth/adapters/secondaries/auth.repository';
|
||||
import { PrismaService } from './src/adapters/secondaries/prisma-service';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService, AuthRepository],
|
||||
exports: [PrismaService, AuthRepository],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
|
||||
import { DatabaseException } from '../../exceptions/DatabaseException';
|
||||
import { ICollection } from '../../interfaces/collection.interface';
|
||||
import { IRepository } from '../../interfaces/repository.interface';
|
||||
import { PrismaService } from './prisma-service';
|
||||
|
||||
/**
|
||||
* Child classes MUST redefined _model property with appropriate model name
|
||||
*/
|
||||
@Injectable()
|
||||
export abstract class PrismaRepository<T> implements IRepository<T> {
|
||||
protected _model: string;
|
||||
|
||||
constructor(protected readonly _prisma: PrismaService) {}
|
||||
|
||||
async findAll(
|
||||
page = 1,
|
||||
perPage = 10,
|
||||
where?: any,
|
||||
include?: any,
|
||||
): Promise<ICollection<T>> {
|
||||
const [data, total] = await this._prisma.$transaction([
|
||||
this._prisma[this._model].findMany({
|
||||
where,
|
||||
include,
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
this._prisma[this._model].count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
return Promise.resolve({
|
||||
data,
|
||||
total,
|
||||
});
|
||||
}
|
||||
|
||||
async findOneByUuid(uuid: string): Promise<T> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].findUnique({
|
||||
where: { uuid },
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(where: any, include?: any): Promise<T> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].findFirst({
|
||||
where: where,
|
||||
include: include,
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(PrismaClientKnownRequestError.name, e.code);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO : using any is not good, but needed for nested entities
|
||||
// TODO : Refactor for good clean architecture ?
|
||||
async create(entity: Partial<T> | any, include?: any): Promise<T> {
|
||||
try {
|
||||
const res = await this._prisma[this._model].create({
|
||||
data: entity,
|
||||
include: include,
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async update(uuid: string, entity: Partial<T>): Promise<T> {
|
||||
try {
|
||||
const updatedEntity = await this._prisma[this._model].update({
|
||||
where: { uuid },
|
||||
data: entity,
|
||||
});
|
||||
return updatedEntity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async updateWhere(
|
||||
where: any,
|
||||
entity: Partial<T> | any,
|
||||
include?: any,
|
||||
): Promise<T> {
|
||||
try {
|
||||
const updatedEntity = await this._prisma[this._model].update({
|
||||
where: where,
|
||||
data: entity,
|
||||
include: include,
|
||||
});
|
||||
|
||||
return updatedEntity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async delete(uuid: string): Promise<void> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].delete({
|
||||
where: { uuid },
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit {
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async enableShutdownHooks(app: INestApplication) {
|
||||
this.$on('beforeExit', async () => {
|
||||
await app.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
3
src/modules/database/src/domain/authnz-repository.ts
Normal file
3
src/modules/database/src/domain/authnz-repository.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { PrismaRepository } from '../adapters/secondaries/prisma-repository.abstract';
|
||||
|
||||
export class AuthNZRepository<T> extends PrismaRepository<T> {}
|
||||
24
src/modules/database/src/exceptions/DatabaseException.ts
Normal file
24
src/modules/database/src/exceptions/DatabaseException.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
export class DatabaseException implements Error {
|
||||
name: string;
|
||||
message: string;
|
||||
|
||||
constructor(
|
||||
private _type: string = 'unknown',
|
||||
private _code: string = '',
|
||||
message?: string,
|
||||
) {
|
||||
this.name = 'DatabaseException';
|
||||
this.message = message ?? 'An error occured with the database.';
|
||||
if (this.message.includes('Unique constraint failed')) {
|
||||
this.message = 'Already exists.';
|
||||
}
|
||||
}
|
||||
|
||||
get type(): string {
|
||||
return this._type;
|
||||
}
|
||||
|
||||
get code(): string {
|
||||
return this._code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface ICollection<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
16
src/modules/database/src/interfaces/repository.interface.ts
Normal file
16
src/modules/database/src/interfaces/repository.interface.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { ICollection } from './collection.interface';
|
||||
|
||||
export interface IRepository<T> {
|
||||
findAll(
|
||||
page: number,
|
||||
perPage: number,
|
||||
params?: any,
|
||||
include?: any,
|
||||
): Promise<ICollection<T>>;
|
||||
findOne(where: any, include?: any): Promise<T>;
|
||||
findOneByUuid(uuid: string, include?: any): Promise<T>;
|
||||
create(entity: Partial<T> | any, include?: any): Promise<T>;
|
||||
update(uuid: string, entity: Partial<T>, include?: any): Promise<T>;
|
||||
updateWhere(where: any, entity: Partial<T> | any, include?: any): Promise<T>;
|
||||
delete(uuid: string): Promise<void>;
|
||||
}
|
||||
244
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
244
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
@@ -0,0 +1,244 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PrismaService } from '../../src/adapters/secondaries/prisma-service';
|
||||
import { PrismaRepository } from '../../src/adapters/secondaries/prisma-repository.abstract';
|
||||
import { DatabaseException } from '../../src/exceptions/DatabaseException';
|
||||
|
||||
class FakeEntity {
|
||||
uuid?: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
let entityId = 2;
|
||||
const entityUuid = 'uuid-';
|
||||
const entityName = 'name-';
|
||||
|
||||
const createRandomEntity = (): FakeEntity => {
|
||||
const entity: FakeEntity = {
|
||||
uuid: `${entityUuid}${entityId}`,
|
||||
name: `${entityName}${entityId}`,
|
||||
};
|
||||
|
||||
entityId++;
|
||||
|
||||
return entity;
|
||||
};
|
||||
|
||||
const fakeEntityToCreate: FakeEntity = {
|
||||
name: 'test',
|
||||
};
|
||||
|
||||
const fakeEntityCreated: FakeEntity = {
|
||||
...fakeEntityToCreate,
|
||||
uuid: 'some-uuid',
|
||||
};
|
||||
|
||||
const fakeEntities: FakeEntity[] = [];
|
||||
Array.from({ length: 10 }).forEach(() => {
|
||||
fakeEntities.push(createRandomEntity());
|
||||
});
|
||||
|
||||
@Injectable()
|
||||
class FakePrismaRepository extends PrismaRepository<FakeEntity> {
|
||||
protected _model = 'fake';
|
||||
}
|
||||
|
||||
class FakePrismaService extends PrismaService {
|
||||
fake: any;
|
||||
}
|
||||
|
||||
const mockPrismaService = {
|
||||
$transaction: jest.fn().mockImplementation(async (data: any) => {
|
||||
const entities = await data[0];
|
||||
if (entities.length == 1) {
|
||||
return Promise.resolve([[fakeEntityCreated], 1]);
|
||||
}
|
||||
|
||||
return Promise.resolve([fakeEntities, fakeEntities.length]);
|
||||
}),
|
||||
fake: {
|
||||
create: jest.fn().mockResolvedValue(fakeEntityCreated),
|
||||
|
||||
findMany: jest.fn().mockImplementation((params?: any) => {
|
||||
if (params?.where?.limit == 1) {
|
||||
return Promise.resolve([fakeEntityCreated]);
|
||||
}
|
||||
|
||||
return Promise.resolve(fakeEntities);
|
||||
}),
|
||||
count: jest.fn().mockResolvedValue(fakeEntities.length),
|
||||
|
||||
findUnique: jest.fn().mockImplementation(async (params?: any) => {
|
||||
let entity;
|
||||
|
||||
if (params?.where?.uuid) {
|
||||
entity = fakeEntities.find(
|
||||
(entity) => entity.uuid === params?.where?.uuid,
|
||||
);
|
||||
}
|
||||
|
||||
if (!entity) {
|
||||
throw new Error('no entity');
|
||||
}
|
||||
|
||||
return entity;
|
||||
}),
|
||||
|
||||
findFirst: jest.fn().mockImplementation((params?: any) => {
|
||||
if (params?.where?.name) {
|
||||
return Promise.resolve(
|
||||
fakeEntities.find((entity) => entity.name === params?.where?.name),
|
||||
);
|
||||
}
|
||||
}),
|
||||
|
||||
update: jest.fn().mockImplementation((params: any) => {
|
||||
const entity = fakeEntities.find(
|
||||
(entity) => entity.uuid === params.where.uuid,
|
||||
);
|
||||
Object.entries(params.data).map(([key, value]) => {
|
||||
entity[key] = value;
|
||||
});
|
||||
|
||||
return Promise.resolve(entity);
|
||||
}),
|
||||
|
||||
delete: jest.fn().mockImplementation((params: any) => {
|
||||
let found = false;
|
||||
|
||||
fakeEntities.forEach((entity, index) => {
|
||||
if (entity.uuid === params?.where?.uuid) {
|
||||
found = true;
|
||||
fakeEntities.splice(index, 1);
|
||||
}
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
throw new Error();
|
||||
}
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
describe('PrismaRepository', () => {
|
||||
let fakeRepository: FakePrismaRepository;
|
||||
let prisma: FakePrismaService;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
FakePrismaRepository,
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: mockPrismaService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
fakeRepository = module.get<FakePrismaRepository>(FakePrismaRepository);
|
||||
prisma = module.get<PrismaService>(PrismaService) as FakePrismaService;
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(fakeRepository).toBeDefined();
|
||||
expect(prisma).toBeDefined();
|
||||
});
|
||||
|
||||
describe('findAll', () => {
|
||||
it('should return an array of entities', async () => {
|
||||
jest.spyOn(prisma.fake, 'findMany');
|
||||
jest.spyOn(prisma.fake, 'count');
|
||||
jest.spyOn(prisma, '$transaction');
|
||||
|
||||
const entities = await fakeRepository.findAll();
|
||||
expect(entities).toStrictEqual({
|
||||
data: fakeEntities,
|
||||
total: fakeEntities.length,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return an array containing only one entity', async () => {
|
||||
const entities = await fakeRepository.findAll(1, 10, { limit: 1 });
|
||||
|
||||
expect(prisma.fake.findMany).toHaveBeenCalledWith({
|
||||
skip: 0,
|
||||
take: 10,
|
||||
where: { limit: 1 },
|
||||
});
|
||||
expect(entities).toEqual({
|
||||
data: [fakeEntityCreated],
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('should create an entity', async () => {
|
||||
jest.spyOn(prisma.fake, 'create');
|
||||
|
||||
const newEntity = await fakeRepository.create(fakeEntityToCreate);
|
||||
expect(newEntity).toBe(fakeEntityCreated);
|
||||
expect(prisma.fake.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should find an entity by uuid', async () => {
|
||||
const entity = await fakeRepository.findOneByUuid(fakeEntities[0].uuid);
|
||||
expect(entity).toBe(fakeEntities[0]);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException if uuid is not found', async () => {
|
||||
await expect(
|
||||
fakeRepository.findOneByUuid('wrong-uuid'),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('should update an entity', async () => {
|
||||
const newName = 'random-name';
|
||||
|
||||
await fakeRepository.update(fakeEntities[0].uuid, {
|
||||
name: newName,
|
||||
});
|
||||
expect(fakeEntities[0].name).toBe(newName);
|
||||
});
|
||||
|
||||
it("should throw an exception if an entity doesn't exist", async () => {
|
||||
await expect(
|
||||
fakeRepository.update('fake-uuid', { name: 'error' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('should delete an entity', async () => {
|
||||
const savedUuid = fakeEntities[0].uuid;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const res = await fakeRepository.delete(savedUuid);
|
||||
|
||||
const deletedEntity = fakeEntities.find(
|
||||
(entity) => entity.uuid === savedUuid,
|
||||
);
|
||||
expect(deletedEntity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should throw an exception if an entity doesn't exist", async () => {
|
||||
await expect(fakeRepository.delete('fake-uuid')).rejects.toBeInstanceOf(
|
||||
DatabaseException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should find one entity', async () => {
|
||||
const entity = await fakeRepository.findOne({
|
||||
name: fakeEntities[0].name,
|
||||
});
|
||||
|
||||
expect(entity.name).toBe(fakeEntities[0].name);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user