|
| 1 | +import { Controller, Get, Query, UseGuards } from '@nestjs/common'; |
| 2 | +import { ApiOperation, ApiQuery, ApiSecurity, ApiTags } from '@nestjs/swagger'; |
| 3 | +import { db } from '@trycompai/db'; |
| 4 | +import { AuthContext, OrganizationId } from '../auth/auth-context.decorator'; |
| 5 | +import { HybridAuthGuard } from '../auth/hybrid-auth.guard'; |
| 6 | +import { PermissionGuard } from '../auth/permission.guard'; |
| 7 | +import { RequirePermission } from '../auth/require-permission.decorator'; |
| 8 | +import type { AuthContext as AuthContextType } from '../auth/types'; |
| 9 | + |
| 10 | +@ApiTags('Audit Logs') |
| 11 | +@Controller({ path: 'audit-logs', version: '1' }) |
| 12 | +@UseGuards(HybridAuthGuard, PermissionGuard) |
| 13 | +@ApiSecurity('apikey') |
| 14 | +export class AuditLogController { |
| 15 | + @Get() |
| 16 | + @RequirePermission('app', 'read') |
| 17 | + @ApiOperation({ summary: 'Get audit logs filtered by entity type and ID' }) |
| 18 | + @ApiQuery({ name: 'entityType', required: false, description: 'Filter by entity type (e.g. policy, task, control)' }) |
| 19 | + @ApiQuery({ name: 'entityId', required: false, description: 'Filter by entity ID' }) |
| 20 | + @ApiQuery({ name: 'take', required: false, description: 'Number of logs to return (max 100, default 50)' }) |
| 21 | + async getAuditLogs( |
| 22 | + @OrganizationId() organizationId: string, |
| 23 | + @AuthContext() authContext: AuthContextType, |
| 24 | + @Query('entityType') entityType?: string, |
| 25 | + @Query('entityId') entityId?: string, |
| 26 | + @Query('take') take?: string, |
| 27 | + ) { |
| 28 | + // organizationId comes from auth context (not user input) — ensures tenant isolation |
| 29 | + const where: Record<string, unknown> = { organizationId }; |
| 30 | + if (entityType) where.entityType = entityType; |
| 31 | + if (entityId) where.entityId = entityId; |
| 32 | + |
| 33 | + const parsedTake = take |
| 34 | + ? Math.min(100, Math.max(1, parseInt(take, 10) || 50)) |
| 35 | + : 50; |
| 36 | + |
| 37 | + const logs = await db.auditLog.findMany({ |
| 38 | + where, |
| 39 | + include: { |
| 40 | + user: { |
| 41 | + select: { id: true, name: true, email: true, image: true }, |
| 42 | + }, |
| 43 | + member: true, |
| 44 | + organization: true, |
| 45 | + }, |
| 46 | + orderBy: { timestamp: 'desc' }, |
| 47 | + take: parsedTake, |
| 48 | + }); |
| 49 | + |
| 50 | + return { |
| 51 | + data: logs, |
| 52 | + authType: authContext.authType, |
| 53 | + ...(authContext.userId && { |
| 54 | + authenticatedUser: { |
| 55 | + id: authContext.userId, |
| 56 | + email: authContext.userEmail, |
| 57 | + }, |
| 58 | + }), |
| 59 | + }; |
| 60 | + } |
| 61 | +} |
0 commit comments