switch to using user token for auth for rigbuilder

This commit is contained in:
makearmy 2025-09-27 11:12:59 -04:00
parent e58f5aaff1
commit 5c6962f4a5

View file

@ -1,44 +1,52 @@
// app/api/options/rig_type/route.ts
export const dynamic = "force-dynamic";
import { NextRequest, NextResponse } from "next/server";
const BASE = process.env.DIRECTUS_URL!;
const SUBMIT = process.env.DIRECTUS_TOKEN_SUBMIT || "";
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
const SUBMIT = process.env.DIRECTUS_TOKEN_SUBMIT || ""; // fallback for anon contexts
const ADMIN = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || ""; // last-resort fallback
const q = `/items/user_rig_type?fields=id,name&sort=sort`;
const url = (BASE || "").replace(/\/$/, "") + q;
const PATH = `/items/user_rig_type?fields=id,name&sort=sort`;
async function tryFetch(headers: HeadersInit) {
const res = await fetch(url, { headers });
async function dFetch(auth?: string) {
const headers: HeadersInit = { Accept: "application/json" };
if (auth) headers.Authorization = `Bearer ${auth}`;
const res = await fetch(`${BASE}${PATH}`, { headers, cache: "no-store" });
const text = await res.text().catch(() => "");
let json: any = null;
try {
json = text ? JSON.parse(text) : null;
} catch {}
try { json = text ? JSON.parse(text) : null; } catch {}
return { res, json, text };
}
export async function GET(_req: NextRequest) {
export async function GET(req: NextRequest) {
try {
// 1) Try with submit token
let { res, json, text } = await tryFetch({
Accept: "application/json",
...(SUBMIT ? { Authorization: `Bearer ${SUBMIT}` } : {}),
});
// 1) Prefer the *user's* token set by login
const userAt = req.cookies.get("ma_at")?.value;
// 2) If forbidden, retry anonymously (Public role)
if (res.status === 403) {
({ res, json, text } = await tryFetch({ Accept: "application/json" }));
let r = await dFetch(userAt);
// 2) If thats forbidden/unauthorized (or theyre logged out), fall back to SUBMIT
if ((r.res.status === 401 || r.res.status === 403) && SUBMIT) {
r = await dFetch(SUBMIT);
}
if (!res.ok) {
// 3) As a final fallback, try ADMIN (useful during migrations/hardening)
if ((r.res.status === 401 || r.res.status === 403) && ADMIN) {
r = await dFetch(ADMIN);
}
if (!r.res.ok) {
return NextResponse.json(
{ error: `Directus ${res.status}: ${text || res.statusText}` },
{ error: `Directus ${r.res.status}: ${r.text || r.res.statusText}` },
{ status: 500 }
);
}
const items: Array<{ id: string | number; name: string }> = json?.data ?? [];
const data = items.map(({ id, name }) => ({ id, label: name }));
const rows: Array<{ id: number | string; name: string }> =
r.json?.data ?? r.json ?? [];
const data = rows.map(({ id, name }) => ({ id, label: name }));
return NextResponse.json({ data }, { status: 200 });
} catch (e: any) {
return NextResponse.json(
@ -47,4 +55,3 @@ export async function GET(_req: NextRequest) {
);
}
}