← back to Omega Watches 2
src/app/api/auditlog/route.ts
43 lines
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { getSession, requireRole } from "@/lib/auth";
export const dynamic = "force-dynamic";
export async function GET(request: NextRequest) {
const session = await getSession(request);
if (!session) {
return NextResponse.json({ success: false, error: { code: "UNAUTHORIZED", message: "Login required" } }, { status: 401 });
}
requireRole(session, ["admin", "auditor"]);
const { searchParams } = new URL(request.url);
const table = searchParams.get("table");
const operation = searchParams.get("operation");
const limit = Math.min(parseInt(searchParams.get("limit") || "100"), 500);
let where = "WHERE 1=1";
const params: any[] = [];
if (table) {
params.push(table);
where += ` AND table_name = $${params.length}`;
}
if (operation) {
params.push(operation);
where += ` AND operation = $${params.length}`;
}
params.push(limit);
const logs = await query(
`SELECT * FROM audit_log ${where} ORDER BY changed_at DESC LIMIT $${params.length}`,
params
);
return NextResponse.json({
success: true,
data: logs,
meta: { total: logs.length, timestamp: new Date().toISOString() },
});
}