69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
import { readFile } from "fs/promises";
|
|
import path from "path";
|
|
import { NextResponse } from "next/server";
|
|
|
|
import { auth } from "@/auth";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { visibleAnnouncementAudiences } from "@/lib/announcement-access";
|
|
|
|
export const runtime = "nodejs";
|
|
|
|
function getUploadPath(attachmentId: string) {
|
|
const uploadDir = path.resolve(
|
|
process.env.UPLOAD_DIR ?? "uploads",
|
|
"announcements",
|
|
);
|
|
return path.join(uploadDir, attachmentId);
|
|
}
|
|
|
|
function contentDisposition(fileName: string) {
|
|
const fallback = fileName.replace(/[^\w.\-]/g, "_");
|
|
return `inline; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
|
|
}
|
|
|
|
export async function GET(
|
|
_request: Request,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
const session = await auth();
|
|
const user = session?.user;
|
|
|
|
if (!user?.id || !user.kitaId) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const { id } = await params;
|
|
const attachment = await prisma.attachment.findFirst({
|
|
where: {
|
|
id,
|
|
announcement: {
|
|
kitaId: user.kitaId,
|
|
audience: { in: visibleAnnouncementAudiences(user) },
|
|
},
|
|
},
|
|
select: {
|
|
id: true,
|
|
fileName: true,
|
|
fileType: true,
|
|
},
|
|
});
|
|
|
|
if (!attachment) {
|
|
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
}
|
|
|
|
try {
|
|
const file = await readFile(getUploadPath(attachment.id));
|
|
return new Response(new Uint8Array(file), {
|
|
headers: {
|
|
"Content-Type": attachment.fileType,
|
|
"Content-Disposition": contentDisposition(attachment.fileName),
|
|
"Cache-Control": "private, no-store",
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error("Anhang konnte nicht gelesen werden:", error);
|
|
return NextResponse.json({ error: "File not found" }, { status: 404 });
|
|
}
|
|
}
|