// app/api/auth/register/route.ts import { NextResponse } from "next/server"; import { loginDirectus } from "@/lib/directus"; export const runtime = "nodejs"; // Base URL (no trailing slash) const API = (process.env.NEXT_PUBLIC_API_BASE_URL || process.env.DIRECTUS_URL || "").replace(/\/$/, ""); // Service token to create users / read roles const SERVICE_TOKEN = process.env.DIRECTUS_SERVICE_TOKEN || process.env.DIRECTUS_STATIC_TOKEN || ""; // Auto login right after signup (default: true) const AUTO_LOGIN = (process.env.SIGNUP_AUTO_LOGIN ?? "1") !== "0"; const secure = process.env.NODE_ENV === "production"; function bad(message: string, status = 400, extra: Record = {}) { return NextResponse.json({ error: message, ...extra }, { status }); } // Resolve the role id for the role named **Users**. No fallbacks. async function getUsersRoleId(): Promise { if (!API) throw new Error("DIRECTUS_URL / NEXT_PUBLIC_API_BASE_URL is not set"); if (!SERVICE_TOKEN) throw new Error("DIRECTUS_SERVICE_TOKEN is not set"); const r = await fetch(`${API}/roles?filter[name][_eq]=Users&fields=id,name&limit=1`, { headers: { Authorization: `Bearer ${SERVICE_TOKEN}`, Accept: "application/json" }, cache: "no-store", }); const j = await r.json().catch(() => ({})); if (!r.ok) { const reason = j?.errors?.[0]?.message || r.statusText; throw new Error(`Failed to query role "Users": ${reason}`); } const id = j?.data?.[0]?.id ?? j?.[0]?.id; if (!id) { throw new Error('Role "Users" not found. Create it in Directus or set DIRECTUS_SERVICE_TOKEN correctly.'); } return String(id); } export async function POST(req: Request) { try { if (!API) return bad("Server misconfiguration: DIRECTUS_URL / NEXT_PUBLIC_API_BASE_URL is not set", 500); if (!SERVICE_TOKEN) { return bad( "Server misconfiguration: DIRECTUS_SERVICE_TOKEN is not set", 500, { hint: "Create a service/static token in Directus Admin and set DIRECTUS_SERVICE_TOKEN." } ); } const body = await req.json().catch(() => ({})); const username = String(body?.username || "").trim(); const email = String(body?.email || "").trim().toLowerCase(); // optional const password = String(body?.password || "").trim(); const first_name = String(body?.first_name || "").trim() || undefined; const last_name = String(body?.last_name || "").trim() || undefined; if (!username) return bad("Username is required"); if (!password || password.length < 8) return bad("Password must be at least 8 characters"); // Only accept the "Users" role const roleId = await getUsersRoleId(); // Create the user in Directus using service token const createPayload: Record = { status: "active", // change to "pending" if you want a verification flow role: roleId, username, password, }; if (email) createPayload.email = email; if (first_name) createPayload.first_name = first_name; if (last_name) createPayload.last_name = last_name; const createRes = await fetch(`${API}/users`, { method: "POST", headers: { Authorization: `Bearer ${SERVICE_TOKEN}`, "Content-Type": "application/json", Accept: "application/json", }, body: JSON.stringify(createPayload), }); const createJson = await createRes.json().catch(() => ({})); if (!createRes.ok) { const reason = createJson?.errors?.[0]?.message || createJson?.error || createRes.statusText || "Registration failed"; return bad("Registration failed", createRes.status, { debug: reason }); } const user = createJson?.data ?? createJson; const res = NextResponse.json({ ok: true, user: { id: user?.id, email: user?.email, username: user?.username }, }); // Optional auto-login after signup if (AUTO_LOGIN && (email || username)) { try { // Prefer email when available; otherwise attempt username if your Directus login allows it const identifier = email || username; const auth = await loginDirectus(identifier, password); const access = auth?.access_token ?? auth?.data?.access_token; const expiresSec = auth?.expires ?? auth?.data?.expires; if (access) { const maxAge = typeof expiresSec === "number" ? Math.max(0, Math.floor(expiresSec)) : 60 * 60 * 8; res.cookies.set({ name: "ma_at", value: access, httpOnly: true, sameSite: "lax", secure, path: "/", maxAge, }); } } catch { // Ignore auto-login failure; user creation succeeded. } } return res; } catch (e: any) { return bad(e?.message || "Registration error", e?.status || 500); } }