57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { auth } from "@/lib/auth";
|
|
import { deleteBackup } from "@/lib/backup/manager";
|
|
import { db } from "@/lib/db";
|
|
import { backups } from "@/lib/db/schema";
|
|
import { eq } from "drizzle-orm";
|
|
import * as fs from "node:fs";
|
|
|
|
export async function DELETE(
|
|
req: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
const session = await auth.api.getSession({ headers: req.headers });
|
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
if (!["superadmin", "admin"].includes(session.user.role ?? "")) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const { id } = await params;
|
|
try {
|
|
await deleteBackup(id);
|
|
return NextResponse.json({ success: true });
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : "Unknown error";
|
|
return NextResponse.json({ error: message }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function GET(
|
|
req: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
const session = await auth.api.getSession({ headers: req.headers });
|
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
|
|
const { id } = await params;
|
|
const backup = await db.select().from(backups).where(eq(backups.id, id)).get();
|
|
if (!backup) return NextResponse.json({ error: "Backup not found" }, { status: 404 });
|
|
if (backup.status !== "completed") {
|
|
return NextResponse.json({ error: "Backup not ready" }, { status: 400 });
|
|
}
|
|
|
|
if (!backup.path || !fs.existsSync(backup.path)) {
|
|
return NextResponse.json({ error: "Backup file not found on disk" }, { status: 404 });
|
|
}
|
|
|
|
const fileBuffer = fs.readFileSync(backup.path);
|
|
return new NextResponse(fileBuffer, {
|
|
headers: {
|
|
"Content-Disposition": `attachment; filename="${encodeURIComponent(backup.name)}"`,
|
|
"Content-Type": "application/zip",
|
|
"Content-Length": String(fileBuffer.length),
|
|
"X-Content-Type-Options": "nosniff",
|
|
},
|
|
});
|
|
}
|