49 lines
1.9 KiB
TypeScript
49 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { auth } from "@/lib/auth";
|
|
import { checkRateLimit, getClientIp } from "@/lib/security/rateLimit";
|
|
import { createBackup, listBackups, BackupType } from "@/lib/backup/manager";
|
|
import { z } from "zod";
|
|
|
|
const CreateBackupSchema = z.object({
|
|
type: z.enum(["worlds", "plugins", "config", "full"]),
|
|
});
|
|
|
|
export async function GET(req: NextRequest) {
|
|
const session = await auth.api.getSession({ headers: req.headers });
|
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
|
|
const ip = getClientIp(req);
|
|
const { allowed } = checkRateLimit(ip);
|
|
if (!allowed) return NextResponse.json({ error: "Too many requests" }, { status: 429 });
|
|
|
|
const backups = await listBackups();
|
|
return NextResponse.json({ backups });
|
|
}
|
|
|
|
export async function POST(req: NextRequest) {
|
|
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 ip = getClientIp(req);
|
|
const { allowed } = checkRateLimit(ip, 5); // Strict limit for backup creation
|
|
if (!allowed) return NextResponse.json({ error: "Too many requests" }, { status: 429 });
|
|
|
|
let body: z.infer<typeof CreateBackupSchema>;
|
|
try {
|
|
body = CreateBackupSchema.parse(await req.json());
|
|
} catch {
|
|
return NextResponse.json({ error: "Invalid request" }, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
const id = await createBackup(body.type as BackupType, session.user.id);
|
|
return NextResponse.json({ success: true, id }, { status: 201 });
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : "Backup failed";
|
|
return NextResponse.json({ error: message }, { status: 500 });
|
|
}
|
|
}
|