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
3 changes: 2 additions & 1 deletion backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { cdnConfig } from './config/cdn.config';
import { stellarConfig } from './config/stellar.config';
import { smsConfig } from './config/sms.config';
import { AuthModule } from './auth/auth.module';
import { ObservabilityModule } from './modules/observability/observability.module';
import { AuditModule } from './audit/audit.module';

// Feature Modules
import { UsersModule } from './modules/users/users.module';
Expand Down Expand Up @@ -114,6 +114,7 @@ ThrottlerModule.forRoot([{
LostPetsModule,
AllergiesModule,
ConditionsModule,
AuditModule,

VerificationModule,
GdprModule,
Expand Down
18 changes: 18 additions & 0 deletions backend/src/audit/audit.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuditController } from './audit.controller';

describe('AuditController', () => {
let controller: AuditController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuditController],
}).compile();

controller = module.get<AuditController>(AuditController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
12 changes: 12 additions & 0 deletions backend/src/audit/audit.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AuditService } from './audit.service';

@Controller('audit')
export class AuditController {
constructor(private readonly auditService: AuditService) {}

@Get()
getLogs() {
return this.auditService.findAll();
}
}
31 changes: 31 additions & 0 deletions backend/src/audit/audit.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';

@Entity('audit_logs')
export class AuditLog {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column()
action: string;

@Column({ nullable: true })
entity: string;

@Column({ nullable: true })
entityId: string;

@Column({ type: 'json', nullable: true })
oldData: any;

@Column({ type: 'json', nullable: true })
newData: any;

@Column()
userId: string;

@Column()
hash: string;

@CreateDateColumn()
createdAt: Date;
}
34 changes: 34 additions & 0 deletions backend/src/audit/audit.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { tap } from 'rxjs';
import { AuditService } from './audit.service';

@Injectable()
export class AuditInterceptor implements NestInterceptor {
constructor(private readonly auditService: AuditService) {}

intercept(context: ExecutionContext, next: CallHandler) {
const request = context.switchToHttp().getRequest();

const { method, url, body, user } = request;

return next.handle().pipe(
tap(async (responseData) => {
try {
await this.auditService.logAction({
action: method,
entity: url,
userId: user?.id || 'anonymous',
newData: body,
});
} catch (err) {
console.error('Audit log failed:', err);
}
}),
);
}
}
13 changes: 13 additions & 0 deletions backend/src/audit/audit.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuditLog } from './audit.entity';
import { AuditService } from './audit.service';
import { AuditController } from './audit.controller';

@Module({
imports: [TypeOrmModule.forFeature([AuditLog])],
controllers: [AuditController],
providers: [AuditService],
exports: [AuditService],
})
export class AuditModule {}
18 changes: 18 additions & 0 deletions backend/src/audit/audit.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuditService } from './audit.service';

describe('AuditService', () => {
let service: AuditService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuditService],
}).compile();

service = module.get<AuditService>(AuditService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
37 changes: 37 additions & 0 deletions backend/src/audit/audit.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AuditLog } from './audit.entity';
import { Repository } from 'typeorm';
import * as crypto from 'crypto';

@Injectable()
export class AuditService {
constructor(
@InjectRepository(AuditLog)
private readonly auditRepo: Repository<AuditLog>,
) {}

generateHash(data: any): string {
return crypto
.createHash('sha256')
.update(JSON.stringify(data))
.digest('hex');
}

async logAction(payload: Partial<AuditLog>) {
const hash = this.generateHash(payload);

const log = this.auditRepo.create({
...payload,
hash,
});

return this.auditRepo.save(log);
}

async findAll() {
return this.auditRepo.find({
order: { createdAt: 'DESC' },
});
}
}
4 changes: 4 additions & 0 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ import { ConfigService } from '@nestjs/config';
import { NestExpressApplication } from '@nestjs/platform-express';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { AuditInterceptor } from './audit/audit.interceptor';
import { AuditService } from './audit/audit.service';

async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const configService = app.get(ConfigService);
const auditService = app.get(AuditService);
app.useGlobalInterceptors(new AuditInterceptor(auditService));

// Trust proxy for correct IP address detection
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
Expand Down
Loading