claims route to async

This commit is contained in:
makearmy 2025-09-27 22:51:37 -04:00
parent c93daeda4b
commit 7c56170747

View file

@ -2,57 +2,51 @@
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
const API =
process.env.DIRECTUS_URL /* server-only */ ??
process.env.NEXT_PUBLIC_API_BASE_URL /* fallback */;
const ALLOWED = new Set([
'settings_fiber',
'settings_uv',
'settings_co2gal',
'settings_co2gan',
'projects',
]);
const API = process.env.NEXT_PUBLIC_API_BASE_URL!; // e.g. https://directus.your.tld
export async function POST(req: Request) {
let body: any;
try {
body = await req.json();
const { target_collection, target_id } = await req.json();
if (!target_collection || !target_id) {
return NextResponse.json(
{ error: 'Missing target_collection or target_id' },
{ status: 400 }
);
}
// Next 15: cookies() is async
const jar = await cookies();
const token =
jar.get('directus_access_token')?.value ??
jar.get('ma_at')?.value ??
'';
if (!token) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const r = await fetch(`${API}/items/user_claims`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ target_collection, target_id }),
cache: 'no-store',
});
const data = await r.json().catch(() => ({} as any));
if (!r.ok) {
return NextResponse.json(
{ error: data?.errors?.[0]?.message ?? data?.message ?? 'Directus error' },
{ status: r.status }
);
}
return NextResponse.json({ ok: true, data }, { status: 200 });
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
const { target_collection, target_id } = body ?? {};
if (!ALLOWED.has(String(target_collection)) || target_id == null) {
return NextResponse.json({ error: 'Invalid target' }, { status: 400 });
}
const token =
cookies().get('directus_access_token')?.value ??
cookies().get('ma_at')?.value ??
'';
if (!token) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const r = await fetch(`${API}/items/user_claims`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
Accept: 'application/json',
},
body: JSON.stringify({ target_collection, target_id }),
cache: 'no-store',
next: { revalidate: 0 },
});
const data = await r.json().catch(() => ({}));
if (!r.ok) {
const msg = data?.errors?.[0]?.message ?? data?.message ?? 'Directus error';
return NextResponse.json({ error: msg }, { status: r.status });
}
return NextResponse.json({ ok: true, data }, { status: 200 });
}