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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- CreateIndex
CREATE INDEX "idx_audit_logs_created_at_desc" ON "audit_logs"("created_at" DESC);

-- CreateIndex
CREATE INDEX "idx_audit_logs_type_created_at" ON "audit_logs"("type", "created_at" DESC);
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,7 @@ model AuditLog {
@@id([id, createdAt])
@@index([userId], map: "idx_audit_logs_user_id")
@@index([userEmail], map: "idx_audit_logs_user_email")
@@index([createdAt(sort: Desc)], map: "idx_audit_logs_created_at_desc")
@@index([type, createdAt(sort: Desc)], map: "idx_audit_logs_type_created_at")
@@map("audit_logs")
}
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ScheduleModule } from '@nestjs/schedule'
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { AuditLogModule } from './audit-log/audit-log.module'
import { AuthInfrastructureModule } from './auth/auth-infrastructure.module'
import { AuthModule } from './auth/auth.module'
import { AllExceptionsFilter } from './common/filter'
Expand Down Expand Up @@ -47,6 +48,7 @@ import { UserModule } from './user/user.module'
}),
ScheduleModule.forRoot(),
AlsModule,
AuditLogModule,
],
controllers: [AppController],
providers: [
Expand Down
47 changes: 47 additions & 0 deletions src/audit-log/audit-log.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Test, TestingModule } from '@nestjs/testing'
import { AuditLogController } from './audit-log.controller'
import { AuditLogService } from './audit-log.service'
import { GetAuditLogsQueryDto } from './dto'

describe('AuditLogController', () => {
let controller: AuditLogController

const mockAuditLogService = {
findAllAuditLogs: jest.fn(),
}

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuditLogController],
providers: [
{
provide: AuditLogService,
useValue: mockAuditLogService,
},
],
}).compile()

controller = module.get<AuditLogController>(AuditLogController)
})

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

describe('getAuditLogs', () => {
it('should call auditLogService.findAllAuditLogs with correct parameters', async () => {
const userRole = 'ADMIN'
const dto: GetAuditLogsQueryDto = { page: 1, limit: 10 }

mockAuditLogService.findAllAuditLogs.mockResolvedValue('result' as any)

const result = await controller.getAuditLogs(userRole, dto)

expect(mockAuditLogService.findAllAuditLogs).toHaveBeenCalledWith(
userRole,
dto,
)
expect(result).toBe('result')
})
})
})
19 changes: 19 additions & 0 deletions src/audit-log/audit-log.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Controller, Get, Query } from '@nestjs/common'
import { Role } from 'generated/prisma/enums'
import { Roles, User } from 'src/auth/decorator'
import { AuditLogService } from './audit-log.service'
import { GetAuditLogsQueryDto } from './dto'

@Controller('audit-logs')
export class AuditLogController {
constructor(private readonly auditLogService: AuditLogService) {}

@Roles(Role.SUPER_ADMIN, Role.ADMIN)
@Get()
getAuditLogs(
@User('role') userRole: string,
@Query() getAuditLogsQueryDto: GetAuditLogsQueryDto,
) {
return this.auditLogService.findAllAuditLogs(userRole, getAuditLogsQueryDto)
}
}
11 changes: 11 additions & 0 deletions src/audit-log/audit-log.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common'
import { PaginationModule } from 'src/common/pagination/pagination.module'
import { AuditLogController } from './audit-log.controller'
import { AuditLogService } from './audit-log.service'

@Module({
imports: [PaginationModule],
controllers: [AuditLogController],
providers: [AuditLogService],
})
export class AuditLogModule {}
124 changes: 124 additions & 0 deletions src/audit-log/audit-log.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { Test, TestingModule } from '@nestjs/testing'
import type { AuditLog } from 'generated/prisma/client'
import { Paginated } from 'src/common/pagination/interfaces'
import { PaginationProvider } from 'src/common/pagination/pagination.provider'
import { PrismaService } from 'src/infra/prisma/prisma.service'
import { AuditLogService } from './audit-log.service'
import { GetAuditLogsQueryDto } from './dto'

describe('AuditLogService', () => {
let service: AuditLogService
let prisma: PrismaService
let paginationProvider: PaginationProvider

const mockPrismaService = {
auditLog: {
findMany: jest.fn(),
count: jest.fn(),
},
}

const mockPaginationProvider = {
paginateQuery: jest.fn(),
}

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuditLogService,
{
provide: PrismaService,
useValue: mockPrismaService,
},
{
provide: PaginationProvider,
useValue: mockPaginationProvider,
},
],
}).compile()

service = module.get<AuditLogService>(AuditLogService)
prisma = module.get<PrismaService>(PrismaService)
paginationProvider = module.get<PaginationProvider>(PaginationProvider)
jest.clearAllMocks()
})

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

describe('findAllAuditLogs', () => {
it('should query logs correctly for ADMIN', async () => {
const dto: GetAuditLogsQueryDto = {
orderBy: 'createdAt',
order: 'desc',
}

const paginateSpy = jest
.spyOn(paginationProvider, 'paginateQuery')
.mockResolvedValue({
data: [],
meta: {
totalCount: 0,
itemsPerPage: 10,
totalPages: 0,
currentPage: 1,
},
} as unknown as Paginated<AuditLog>)

await service.findAllAuditLogs('ADMIN', dto)

expect(paginateSpy).toHaveBeenCalledWith(
prisma.auditLog,
dto,
expect.objectContaining({
where: expect.objectContaining({
type: {
not: 'ERROR',
contains: undefined,
},
}) as Record<string, unknown>,
orderBy: { createdAt: 'desc' },
}),
)
})

it('should query logs correctly for SUPER_ADMIN', async () => {
const dto: GetAuditLogsQueryDto = {
orderBy: 'type',
order: 'asc',
type: 'CREATE',
userId: '1',
}

const paginateSpy = jest
.spyOn(paginationProvider, 'paginateQuery')
.mockResolvedValue({
data: [],
meta: {
totalCount: 0,
itemsPerPage: 10,
totalPages: 0,
currentPage: 1,
},
} as unknown as Paginated<AuditLog>)

await service.findAllAuditLogs('SUPER_ADMIN', dto)

expect(paginateSpy).toHaveBeenCalledWith(
prisma.auditLog,
dto,
expect.objectContaining({
where: expect.objectContaining({
type: {
not: undefined,
contains: 'CREATE',
},
userId: '1',
}) as Record<string, unknown>,
orderBy: { type: 'asc' },
}),
)
})
})
})
67 changes: 67 additions & 0 deletions src/audit-log/audit-log.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Injectable } from '@nestjs/common'
import { PaginationProvider } from 'src/common/pagination/pagination.provider'
import { PrismaService } from 'src/infra/prisma/prisma.service'
import { GetAuditLogsQueryDto } from './dto'

@Injectable()
export class AuditLogService {
constructor(
private readonly prisma: PrismaService,
private readonly paginationProvider: PaginationProvider,
) {}

public async findAllAuditLogs(
userRole: string,
getAuditLogsQueryDto: GetAuditLogsQueryDto,
) {
// order query
const orderByField = getAuditLogsQueryDto.orderBy
const orderDirection = getAuditLogsQueryDto.order === 'asc' ? 'asc' : 'desc'
// data query
const { monthStart, monthEnd } = this.getDateFallbacks()
const fromDate = new Date(getAuditLogsQueryDto.from ?? monthStart)
const toDate = new Date(getAuditLogsQueryDto.to ?? monthEnd)
toDate.setDate(toDate.getDate() + 1)

return await this.paginationProvider.paginateQuery(
this.prisma.auditLog,
getAuditLogsQueryDto,
{
where: {
createdAt: {
gte: fromDate,
lt: toDate,
},
type: {
not: userRole === 'ADMIN' ? 'ERROR' : undefined,
contains: getAuditLogsQueryDto.type ?? undefined,
},
...(getAuditLogsQueryDto.userId && {
userId: getAuditLogsQueryDto.userId,
}),
...(getAuditLogsQueryDto.userEmail && {
userEmail: {
equals: getAuditLogsQueryDto.userEmail,
mode: 'insensitive',
},
}),
},
orderBy: {
[orderByField!]: orderByField ? orderDirection : undefined,
},
},
)
}

private getDateFallbacks() {
const now = new Date()
const monthStart = new Date(
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
)
const monthEnd = new Date(
Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0),
)

return { monthStart, monthEnd }
}
}
5 changes: 5 additions & 0 deletions src/audit-log/constant/audit-log-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const auditLogType = {
CREATE: 'CREATE',
UPDATA: 'UPDATE',
ERROR: 'ERROR',
}
1 change: 1 addition & 0 deletions src/audit-log/constant/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './audit-log-type'
34 changes: 34 additions & 0 deletions src/audit-log/dto/getAuditLogs.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Type } from 'class-transformer'
import { IsDateString, IsEmail, IsIn, IsInt, IsOptional } from 'class-validator'
import { PaginationQueryDto } from 'src/common/pagination/dto'

export class GetAuditLogsQueryDto extends PaginationQueryDto {
@IsOptional()
@IsIn(['createdAt', 'type', 'requestUrl', 'requestMethod'])
orderBy?: string

@IsOptional()
@IsIn(['asc', 'desc'])
order?: 'asc' | 'desc'

@IsOptional()
@IsDateString()
from?: string

@IsOptional()
@IsDateString()
to?: string

@IsOptional()
@IsIn(['CREATE', 'UPDATE', 'DELETE', 'ERROR'])
type?: string

@Type(() => Number)
@IsOptional()
@IsInt()
userId?: string

@IsOptional()
@IsEmail()
userEmail?: string
}
1 change: 1 addition & 0 deletions src/audit-log/dto/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './getAuditLogs.dto'
7 changes: 1 addition & 6 deletions src/common/filter/all-exceptions.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,10 @@ import {
HttpStatus,
} from '@nestjs/common'
import { Request, Response } from 'express'
import { auditLogType } from 'src/audit-log/constant'
import { REQUEST_USER_KEY } from 'src/auth/guard'
import { PrismaService } from 'src/infra/prisma/prisma.service'

const auditLogType = {
CREATE: 'CREATE',
UPDATA: 'UPDATE',
ERROR: 'ERROR',
}

@Catch() // Leaving this empty catches EVERYTHING
export class AllExceptionsFilter implements ExceptionFilter {
constructor(private readonly prisma: PrismaService) {}
Expand Down
20 changes: 13 additions & 7 deletions src/infra/prisma/extension/prisma.extension.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { PrismaClient, type Prisma } from 'generated/prisma/client'
import { auditLogType } from 'src/audit-log/constant'
import { AlsService } from 'src/infra/als/als.service'
import { getAuditContext } from '../util'

const auditLogType = {
CREATE: 'CREATE',
UPDATA: 'UPDATE',
ERROR: 'ERROR',
}

export const auditLogExtension = (client: PrismaClient, als: AlsService) => {
return client.$extends({
Expand Down Expand Up @@ -93,3 +87,15 @@ export const auditLogExtension = (client: PrismaClient, als: AlsService) => {
}

export type AuditLogPrismaClient = ReturnType<typeof auditLogExtension>

function getAuditContext(als: AlsService) {
const store = als.getStore()

return {
requestUrl: store?.get('url') as string | undefined,
requestMethod: store?.get('method') as string | undefined,
userId: store?.get('userId') as number | undefined,
userEmail: store?.get('userEmail') as string | undefined,
userIpAddress: store?.get('ip') as string | undefined,
}
}
Loading
Loading