All files / src/app/api/admin/security/events route.ts

0% Statements 0/137
100% Branches 0/0
0% Functions 0/1
0% Lines 0/137

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138                                                                                                                                                                                                                                                                                   
export const dynamic = "force-dynamic";

/**
 * Security Events API Route
 *
 * Provides paginated security events for the admin dashboard.
 * GET - Get paginated security events with filtering
 */

import { NextRequest, NextResponse } from "next/server";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiSuccessResponse,
  ApiErrorResponse,
} from "@/lib/api";
import { prisma } from "@/lib/prisma";
import type {
  SecurityEventType,
  SecuritySeverity,
} from "@/lib/security/security-logger";

interface SecurityEventsResponse {
  events: Array<{
    id: string;
    type: string;
    severity: string;
    userId: number | null;
    ipAddress: string;
    userAgent: string;
    details: unknown;
    timestamp: Date;
    user?: {
      email: string;
      name: string | null;
    } | null;
  }>;
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
}

/**
 * GET /api/admin/security/events
 * Get paginated security events
 * Query params:
 *   - page: number (default 1)
 *   - limit: number (default 50)
 *   - severity: comma-separated severity levels
 *   - type: comma-separated event types
 *   - userId: filter by user ID
 *   - ipAddress: filter by IP address
 *   - since: ISO date string
 */
async function handleGet(
  request: NextRequest
): Promise<
  NextResponse<ApiSuccessResponse<SecurityEventsResponse> | ApiErrorResponse>
> {
  const { searchParams } = new URL(request.url);

  const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
  const limit = Math.min(
    100,
    Math.max(1, parseInt(searchParams.get("limit") || "50", 10))
  );
  const severity = searchParams.get("severity")?.split(",") as
    | SecuritySeverity[]
    | undefined;
  const type = searchParams.get("type")?.split(",") as
    | SecurityEventType[]
    | undefined;
  const userId = searchParams.get("userId")
    ? parseInt(searchParams.get("userId")!, 10)
    : undefined;
  const ipAddress = searchParams.get("ipAddress") || undefined;
  const since = searchParams.get("since")
    ? new Date(searchParams.get("since")!)
    : new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); // Default to last 7 days

  const where = {
    timestamp: { gte: since },
    ...(severity && { severity: { in: severity } }),
    ...(type && { type: { in: type } }),
    ...(userId && { userId }),
    ...(ipAddress && { ipAddress: { contains: ipAddress } }),
  };

  const [events, total] = await Promise.all([
    prisma.securityLog.findMany({
      where,
      include: {
        user: {
          select: {
            email: true,
            name: true,
          },
        },
      },
      orderBy: { timestamp: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.securityLog.count({ where }),
  ]);

  return successResponse({
    events: events.map((e) => ({
      id: e.id,
      type: e.type,
      severity: e.severity,
      userId: e.userId,
      ipAddress: e.ipAddress,
      userAgent: e.userAgent,
      details: e.details,
      timestamp: e.timestamp,
      user: e.user
        ? {
            email: e.user.email,
            name: e.user.name,
          }
        : null,
    })),
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
    },
  });
}

export const GET = withErrorHandling(withAdmin(handleGet));