import { NextResponse } from "next/server"; import { queryOne, query } from "@/lib/db"; import { removeBrandingFile, saveBrandingFile } from "@/lib/branding"; import { authErrorResponse, requireRole } from "@/lib/auth/session"; import { isSameOrigin } from "@/lib/origin"; type AssetKind = "logo" | "favicon"; const ASSET_COLUMN: Record = { logo: "logo_path", favicon: "favicon_path", }; function isAssetKind(value: unknown): value is AssetKind { return value === "logo" || value === "favicon"; } export async function POST(request: Request) { if (!isSameOrigin(request)) { return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 }); } try { await requireRole(["admin"]); const form = await request.formData(); const kind = form.get("kind"); const file = form.get("file"); if (!isAssetKind(kind) || !(file instanceof File)) { return NextResponse.json({ error: "invalid_input" }, { status: 400 }); } if (!file.type.startsWith("image/")) { return NextResponse.json({ error: "invalid_image" }, { status: 400 }); } const old = await queryOne<{ path: string | null }>( `select ${ASSET_COLUMN[kind]} as path from settings where id = 1` ); const ext = file.name.split(".").pop()?.toLowerCase() ?? "png"; const filename = `${kind}-${Date.now()}.${ext}`; const buffer = Buffer.from(await file.arrayBuffer()); await saveBrandingFile(filename, buffer); await query(`update settings set ${ASSET_COLUMN[kind]} = $1 where id = 1`, [filename]); if (old?.path) await removeBrandingFile(old.path); return NextResponse.json({ path: filename }); } catch (err) { const res = authErrorResponse(err); if (res) return res; throw err; } } export async function DELETE(request: Request) { if (!isSameOrigin(request)) { return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 }); } try { await requireRole(["admin"]); const { kind } = (await request.json()) as { kind?: unknown }; if (!isAssetKind(kind)) { return NextResponse.json({ error: "invalid_input" }, { status: 400 }); } const old = await queryOne<{ path: string | null }>( `select ${ASSET_COLUMN[kind]} as path from settings where id = 1` ); await query(`update settings set ${ASSET_COLUMN[kind]} = null where id = 1`); if (old?.path) await removeBrandingFile(old.path); return NextResponse.json({ ok: true }); } catch (err) { const res = authErrorResponse(err); if (res) return res; throw err; } }