Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ import { LegalDocumentsModule } from './legal-documents/legal-documents.module';

import { TrackSuggestionsModule } from './track-suggestions/track-suggestions.module';
import { RankingSnapshotsModule } from './ranking-snapshots/ranking-snapshots.module';
import { AuditLogsModule } from './audit-logs/audit-logs.module';

@Module({
imports: [
AuditLogsModule,
RankingSnapshotsModule,
TrackSuggestionsModule,
LegalDocumentsModule,
Expand Down
39 changes: 39 additions & 0 deletions src/audit-logs/audit-logs.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags, ApiOperation } from '@nestjs/swagger';
import { Roles } from '../roles/roles.decorator';
import { RoleEnum } from '../roles/roles.enum';
import { AuthGuard } from '@nestjs/passport';
import { RolesGuard } from '../roles/roles.guard';
import { AuditLogsService } from './audit-logs.service';
import { FindAllAuditLogsDto } from './dto/find-all-audit-logs.dto';
import { infinityPagination } from '../utils/infinity-pagination';
import { InfinityPaginationResponseDto } from '../utils/dto/infinity-pagination-response.dto';
import { AuditLog } from './domain/audit-log';

@ApiBearerAuth()
@Roles(RoleEnum.admin)
@UseGuards(AuthGuard('jwt'), RolesGuard)
@ApiTags('Audit Logs')
@Controller({
path: 'audit-logs',
version: '1',
})
export class AuditLogsController {
constructor(private readonly auditLogsService: AuditLogsService) {}

@Get()
@ApiOperation({ summary: 'Find all audit logs (Admin only)' })
async findAll(
@Query() query: FindAllAuditLogsDto,
): Promise<InfinityPaginationResponseDto<AuditLog>> {
const page = query?.page ?? 1;
let limit = query?.limit ?? 10;
if (limit > 50) {
limit = 50;
}

const result = await this.auditLogsService.findAll({ page, limit }, query);

return infinityPagination(result, { page, limit });
}
}
14 changes: 14 additions & 0 deletions src/audit-logs/audit-logs.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { AuditLogsService } from './audit-logs.service';
import { AuditLogsController } from './audit-logs.controller';
import { RelationalAuditLogPersistenceModule } from './infrastructure/persistence/relational/relational-persistence.module';

const infrastructurePersistenceModule = RelationalAuditLogPersistenceModule;

@Module({
imports: [infrastructurePersistenceModule],
controllers: [AuditLogsController],
providers: [AuditLogsService],
exports: [AuditLogsService],
})
export class AuditLogsModule {}
82 changes: 82 additions & 0 deletions src/audit-logs/audit-logs.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuditLogsService } from './audit-logs.service';
import { AuditLogRepository } from './infrastructure/persistence/audit-log.repository';
import { AuditActionEnum } from './domain/audit-action.enum';
import { Logger } from '@nestjs/common';

describe('AuditLogsService', () => {
let service: AuditLogsService;
let repository: AuditLogRepository;
let loggerErrorSpy: jest.SpyInstance;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuditLogsService,
{
provide: AuditLogRepository,
useValue: {
create: jest.fn(),
findAllWithPagination: jest.fn(),
},
},
],
}).compile();

service = module.get<AuditLogsService>(AuditLogsService);
repository = module.get<AuditLogRepository>(AuditLogRepository);
loggerErrorSpy = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => {});
});

afterEach(() => {
jest.clearAllMocks();
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('record', () => {
it('should successfully record an audit log', async () => {
const data = {
action: AuditActionEnum.USER_BANNED,
entityType: 'user',
entityId: '123',
};

await service.record(data);
expect(repository.create).toHaveBeenCalledWith(data);
expect(loggerErrorSpy).not.toHaveBeenCalled();
});

it('should not throw if repository.create fails, but should log error', async () => {
const data = {
action: AuditActionEnum.USER_BANNED,
entityType: 'user',
entityId: '123',
};
const error = new Error('DB connection failed');
jest.spyOn(repository, 'create').mockRejectedValue(error);

await expect(service.record(data)).resolves.not.toThrow();
expect(repository.create).toHaveBeenCalledWith(data);
expect(loggerErrorSpy).toHaveBeenCalled();
});
});

describe('findAll', () => {
it('should pass correct params to repository.findAllWithPagination', async () => {
const options = { page: 1, limit: 10 };
const filters = { action: AuditActionEnum.USER_BANNED };

await service.findAll(options, filters);

expect(repository.findAllWithPagination).toHaveBeenCalledWith(
options,
filters,
);
});
});
});
32 changes: 32 additions & 0 deletions src/audit-logs/audit-logs.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Injectable, Logger } from '@nestjs/common';
import { AuditLogRepository } from './infrastructure/persistence/audit-log.repository';
import { CreateAuditLogDto } from './dto/create-audit-log.dto';
import { FindAllAuditLogsDto } from './dto/find-all-audit-logs.dto';
import { IPaginationOptions } from '../utils/types/pagination-options';
import { AuditLog } from './domain/audit-log';

@Injectable()
export class AuditLogsService {
private readonly logger = new Logger(AuditLogsService.name);

constructor(private readonly auditLogRepository: AuditLogRepository) {}

async record(data: CreateAuditLogDto): Promise<void> {
try {
await this.auditLogRepository.create(data);
} catch (error) {
this.logger.error(
`Failed to record audit log: ${error.message}`,
error.stack,
{ data },
);
}
}

async findAll(
options: IPaginationOptions,
filters: FindAllAuditLogsDto,
): Promise<AuditLog[]> {
return this.auditLogRepository.findAllWithPagination(options, filters);
}
}
12 changes: 12 additions & 0 deletions src/audit-logs/domain/audit-action.enum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export enum AuditActionEnum {
SUBMISSION_APPROVED = 'SUBMISSION_APPROVED',
SUBMISSION_REJECTED = 'SUBMISSION_REJECTED',
EVENT_APPROVED = 'EVENT_APPROVED',
EVENT_REJECTED = 'EVENT_REJECTED',
EVENT_CANCELLED = 'EVENT_CANCELLED',
CONTRIBUTION_REPORT_REVIEWED = 'CONTRIBUTION_REPORT_REVIEWED',
USER_ROLE_CHANGED = 'USER_ROLE_CHANGED',
USER_BANNED = 'USER_BANNED',
USER_UNBANNED = 'USER_UNBANNED',
XP_MANUAL_ADJUSTMENT = 'XP_MANUAL_ADJUSTMENT',
}
12 changes: 12 additions & 0 deletions src/audit-logs/domain/audit-log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { AuditActionEnum } from './audit-action.enum';

export class AuditLog {
id: string;
actorUserId: number | null;
action: AuditActionEnum;
entityType: string;
entityId: string;
targetUserId: number | null;
metadata: any | null;

Check warning on line 10 in src/audit-logs/domain/audit-log.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'any' overrides all other types in this union type.

See more on https://sonarcloud.io/project/issues?id=devs-tocantins_api-engajamento2&issues=AZ-qCkm9Ub9ocBXsVLdw&open=AZ-qCkm9Ub9ocBXsVLdw&pullRequest=109
createdAt: Date;
}
34 changes: 34 additions & 0 deletions src/audit-logs/dto/create-audit-log.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { AuditActionEnum } from '../domain/audit-action.enum';
import {
IsEnum,
IsInt,
IsNotEmpty,
IsObject,
IsOptional,
IsString,
} from 'class-validator';

export class CreateAuditLogDto {
@IsOptional()
@IsInt()
actorUserId?: number | null;

@IsEnum(AuditActionEnum)
action: AuditActionEnum;

@IsString()
@IsNotEmpty()
entityType: string;

@IsString()
@IsNotEmpty()
entityId: string;

@IsOptional()
@IsInt()
targetUserId?: number | null;

@IsOptional()
@IsObject()
metadata?: any | null;

Check warning on line 33 in src/audit-logs/dto/create-audit-log.dto.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'any' overrides all other types in this union type.

See more on https://sonarcloud.io/project/issues?id=devs-tocantins_api-engajamento2&issues=AZ-qCkm1Ub9ocBXsVLdv&open=AZ-qCkm1Ub9ocBXsVLdv&pullRequest=109
}
33 changes: 33 additions & 0 deletions src/audit-logs/dto/find-all-audit-logs.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { IsEnum, IsInt, IsOptional, IsString } from 'class-validator';
import { Type } from 'class-transformer';
import { AuditActionEnum } from '../domain/audit-action.enum';

export class FindAllAuditLogsDto {
@IsOptional()
@Type(() => Number)
@IsInt()
page?: number;

@IsOptional()
@Type(() => Number)
@IsInt()
limit?: number;

@IsOptional()
@IsEnum(AuditActionEnum)
action?: AuditActionEnum;

@IsOptional()
@IsString()
entityType?: string;

@IsOptional()
@Type(() => Number)
@IsInt()
actorUserId?: number;

@IsOptional()
@Type(() => Number)
@IsInt()
targetUserId?: number;
}
12 changes: 12 additions & 0 deletions src/audit-logs/infrastructure/persistence/audit-log.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { AuditLog } from '../../domain/audit-log';
import { CreateAuditLogDto } from '../../dto/create-audit-log.dto';
import { FindAllAuditLogsDto } from '../../dto/find-all-audit-logs.dto';
import { IPaginationOptions } from '../../../utils/types/pagination-options';

export abstract class AuditLogRepository {
abstract create(data: CreateAuditLogDto): Promise<AuditLog>;
abstract findAllWithPagination(
options: IPaginationOptions,
filters: FindAllAuditLogsDto,
): Promise<AuditLog[]>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {
Column,
CreateDateColumn,
Entity,
Index,
PrimaryGeneratedColumn,
} from 'typeorm';
import { AuditActionEnum } from '../../../../domain/audit-action.enum';
import { EntityRelationalHelper } from '../../../../../utils/relational-entity-helper';

@Entity({ name: 'audit_log' })
@Index(['entityType', 'entityId'])
export class AuditLogEntity extends EntityRelationalHelper {
@PrimaryGeneratedColumn('uuid')
id: string;

@Index()
@Column({ type: 'int', nullable: true })
actorUserId: number | null;

@Column({ type: 'varchar', length: 100 })
action: AuditActionEnum;

@Column({ type: 'varchar', length: 100 })
entityType: string;

@Column({ type: 'varchar', length: 100 })
entityId: string;

@Column({ type: 'int', nullable: true })
targetUserId: number | null;

@Column({ type: 'jsonb', nullable: true })
metadata: any | null;

Check warning on line 34 in src/audit-logs/infrastructure/persistence/relational/entities/audit-log.entity.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'any' overrides all other types in this union type.

See more on https://sonarcloud.io/project/issues?id=devs-tocantins_api-engajamento2&issues=AZ-qCkiJUb9ocBXsVLdu&open=AZ-qCkiJUb9ocBXsVLdu&pullRequest=109

@Index()
@CreateDateColumn()
createdAt: Date;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { AuditLog } from '../../../../domain/audit-log';
import { AuditLogEntity } from '../entities/audit-log.entity';

export class AuditLogMapper {
static toDomain(raw: AuditLogEntity): AuditLog {
const domainEntity = new AuditLog();
domainEntity.id = raw.id;
domainEntity.actorUserId = raw.actorUserId;
domainEntity.action = raw.action;
domainEntity.entityType = raw.entityType;
domainEntity.entityId = raw.entityId;
domainEntity.targetUserId = raw.targetUserId;
domainEntity.metadata = raw.metadata;
domainEntity.createdAt = raw.createdAt;
return domainEntity;
}

static toPersistence(domainEntity: AuditLog): AuditLogEntity {
const persistenceEntity = new AuditLogEntity();
if (domainEntity.id) {
persistenceEntity.id = domainEntity.id;
}
persistenceEntity.actorUserId = domainEntity.actorUserId;
persistenceEntity.action = domainEntity.action;
persistenceEntity.entityType = domainEntity.entityType;
persistenceEntity.entityId = domainEntity.entityId;
persistenceEntity.targetUserId = domainEntity.targetUserId;
persistenceEntity.metadata = domainEntity.metadata;
persistenceEntity.createdAt = domainEntity.createdAt;
return persistenceEntity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { AuditLogRepository } from '../audit-log.repository';
import { AuditLogRelationalRepository } from './repositories/audit-log.repository';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuditLogEntity } from './entities/audit-log.entity';

@Module({
imports: [TypeOrmModule.forFeature([AuditLogEntity])],
providers: [
{
provide: AuditLogRepository,
useClass: AuditLogRelationalRepository,
},
],
exports: [AuditLogRepository],
})
export class RelationalAuditLogPersistenceModule {}
Loading