90 lines
2.3 KiB
TypeScript
90 lines
2.3 KiB
TypeScript
import { BACKEND_URL } from '@/_config/backend';
|
|
import { NextRequest } from 'next/server';
|
|
|
|
export const runtime = 'nodejs';
|
|
export const dynamic = 'force-dynamic';
|
|
|
|
type Context = { params: Promise<{ id: string; path?: string[] }> };
|
|
|
|
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i;
|
|
|
|
const FORWARDED_REQUEST_HEADERS = [
|
|
'content-type',
|
|
'range',
|
|
'if-range',
|
|
];
|
|
|
|
const FORWARDED_RESPONSE_HEADERS = [
|
|
'content-type',
|
|
'content-length',
|
|
'content-range',
|
|
'accept-ranges',
|
|
];
|
|
|
|
// Erlaubt sind nur: "", "file", "units" und "units/<id>".
|
|
function isAllowedPdfPath(path: string[]): boolean {
|
|
if (path.length === 0) {
|
|
return true;
|
|
}
|
|
|
|
if (path.length === 1) {
|
|
return ['file', 'units'].includes(path[0]);
|
|
}
|
|
|
|
if (path.length === 2) {
|
|
return path[0] === 'units' && OBJECT_ID_PATTERN.test(path[1]);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
function copyHeaders(source: Headers, target: Headers, names: string[]): void {
|
|
for (const name of names) {
|
|
const value = source.get(name);
|
|
|
|
if (value) {
|
|
target.set(name, value);
|
|
}
|
|
}
|
|
}
|
|
|
|
async function proxy(request: NextRequest, context: Context) {
|
|
const { id, path = [] } = await context.params;
|
|
|
|
if (!OBJECT_ID_PATTERN.test(id) || !isAllowedPdfPath(path)) {
|
|
return Response.json({ message: 'Ungültiger PDF-Pfad' }, { status: 400 });
|
|
}
|
|
|
|
const pathSuffix = path.length ? '/' + path.join('/') : '';
|
|
const url = new URL(`${BACKEND_URL}/anlage/${id}/pdf${pathSuffix}`);
|
|
url.search = request.nextUrl.search;
|
|
|
|
const headers = new Headers();
|
|
copyHeaders(request.headers, headers, FORWARDED_REQUEST_HEADERS);
|
|
|
|
try {
|
|
const body = request.method === 'GET'
|
|
? undefined
|
|
: await request.arrayBuffer();
|
|
|
|
const response = await fetch(url, {
|
|
method: request.method,
|
|
headers,
|
|
cache: 'no-store',
|
|
body,
|
|
});
|
|
|
|
const outgoing = new Headers({ 'Cache-Control': 'no-store' });
|
|
copyHeaders(response.headers, outgoing, FORWARDED_RESPONSE_HEADERS);
|
|
|
|
return new Response(response.body, {
|
|
status: response.status,
|
|
headers: outgoing,
|
|
});
|
|
} catch {
|
|
return Response.json({ message: 'Keine Verbindung zum Backend' }, { status: 502 });
|
|
}
|
|
}
|
|
|
|
export { proxy as GET, proxy as POST, proxy as PATCH };
|