88 lines
2.5 KiB
TypeScript
88 lines
2.5 KiB
TypeScript
import { cookies } from 'next/headers';
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { sanitizeAuditEvent } from '../../../../lib/ops-data';
|
|
import { SafeAuditEvent } from '../../../../components/ops/types';
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const cookieStore = await cookies();
|
|
const isProduction = process.env.NODE_ENV === 'production';
|
|
const opsToken = isProduction
|
|
? cookieStore.get('__Host-motorsignal_ops')?.value
|
|
: cookieStore.get('__Host-motorsignal_ops')?.value ??
|
|
cookieStore.get('motorsignal_ops')?.value;
|
|
|
|
if (!opsToken) {
|
|
return NextResponse.json(
|
|
{ detail: 'Authentication required.' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
const cursor = request.nextUrl.searchParams.get('cursor');
|
|
const baseUrl = process.env.MOTORSIGNAL_API_BASE_URL ?? 'https://api.motorsignal.app';
|
|
const targetUrl = new URL(`${baseUrl}/api/v1/ops/audit-events`);
|
|
if (cursor) {
|
|
targetUrl.searchParams.set('cursor', cursor);
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(targetUrl.toString(), {
|
|
method: 'GET',
|
|
headers: {
|
|
authorization: `Bearer ${opsToken}`,
|
|
accept: 'application/json',
|
|
},
|
|
cache: 'no-store',
|
|
});
|
|
|
|
if (response.status === 401) {
|
|
return NextResponse.json(
|
|
{ detail: 'Your Operations session has expired.' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
if (response.status === 403) {
|
|
return NextResponse.json(
|
|
{ detail: 'You do not have authority to view Audit.' },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
if (!response.ok) {
|
|
return NextResponse.json(
|
|
{ detail: 'Operations is temporarily unavailable.' },
|
|
{ status: response.status >= 500 ? response.status : 503 }
|
|
);
|
|
}
|
|
|
|
const data = await response.json();
|
|
const rawEvents = Array.isArray(data)
|
|
? data
|
|
: Array.isArray(data?.events)
|
|
? data.events
|
|
: Array.isArray(data?.items)
|
|
? data.items
|
|
: [];
|
|
|
|
const safeEvents: SafeAuditEvent[] = rawEvents
|
|
.map(sanitizeAuditEvent)
|
|
.filter((e: SafeAuditEvent | null): e is SafeAuditEvent => e !== null);
|
|
|
|
const nextCursor = data?.next_cursor ?? data?.cursor ?? null;
|
|
const total = typeof data?.total === 'number' ? data.total : undefined;
|
|
|
|
return NextResponse.json(
|
|
{
|
|
events: safeEvents,
|
|
next_cursor: nextCursor,
|
|
total,
|
|
},
|
|
{ status: 200 }
|
|
);
|
|
} catch {
|
|
return NextResponse.json(
|
|
{ detail: 'Operations is temporarily unavailable.' },
|
|
{ status: 503 }
|
|
);
|
|
}
|
|
}
|