42 lines
1.5 KiB
TypeScript
42 lines
1.5 KiB
TypeScript
import { timingSafeEqual } from "node:crypto";
|
|
import { NextResponse } from "next/server";
|
|
import { getPayload } from "payload";
|
|
import config from "@payload-config";
|
|
import { runAnalyticsCleanup } from "@/lib/analytics/cleanup";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
function safeEqual(a: string, b: string): boolean {
|
|
const bufA = Buffer.from(a);
|
|
const bufB = Buffer.from(b);
|
|
if (bufA.length !== bufB.length) return false;
|
|
return timingSafeEqual(bufA, bufB);
|
|
}
|
|
|
|
/**
|
|
* Intended to be called by an external cron job once daily, e.g.:
|
|
* curl -H "Authorization: Bearer $CRON_SECRET" https://anouma.org/api/cron/analytics-cleanup
|
|
* (a second, separate cron entry from /api/cron/event-reminders - reuses
|
|
* the same CRON_SECRET, no new secret needed)
|
|
*/
|
|
export async function GET(request: Request) {
|
|
const secret = process.env.CRON_SECRET;
|
|
if (!secret) {
|
|
return NextResponse.json({ error: "CRON_SECRET is not configured" }, { status: 500 });
|
|
}
|
|
|
|
const authHeader = request.headers.get("authorization");
|
|
if (!authHeader || !safeEqual(authHeader, `Bearer ${secret}`)) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const payload = await getPayload({ config });
|
|
const result = await runAnalyticsCleanup(payload);
|
|
return NextResponse.json({ ok: true, ...result });
|
|
} catch (error) {
|
|
console.error("analytics-cleanup cron failed", error);
|
|
return NextResponse.json({ error: "Internal error" }, { status: 500 });
|
|
}
|
|
}
|