makearmy-app/app/api/auth/login/route.ts

72 lines
2.9 KiB
TypeScript

// app/api/auth/login/route.ts
import { NextRequest, NextResponse } from "next/server";
import { setAuthCookies } from "@/lib/auth-cookies";
const BASE = process.env.DIRECTUS_URL!;
if (!BASE) console.warn("[auth/login] Missing DIRECTUS_URL");
async function jsonSafe(res: Response) {
const text = await res.text();
try { return { json: text ? JSON.parse(text) : null, text }; }
catch { return { json: null as any, text }; }
}
export async function POST(req: NextRequest) {
try {
const body = await req.json().catch(() => ({}));
const identity: string = (body.identity || body.usernameOrEmail || "").trim();
const password: string = String(body.password || "");
if (!identity || !password) {
return NextResponse.json({ error: "Missing identity or password" }, { status: 400 });
}
// Directus login (username OR email works via "email" field for both)
const loginRes = await fetch(`${BASE}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ email: identity, password }),
});
const { json: loginJson, text: loginText } = await jsonSafe(loginRes);
if (!loginRes.ok) {
const msg =
loginJson?.errors?.[0]?.message ||
loginJson?.message ||
`Directus login failed: ${loginRes.status} ${loginRes.statusText}`;
return NextResponse.json({ error: msg }, { status: 401 });
}
const access = loginJson?.data?.access_token || loginJson?.access_token;
const refresh = loginJson?.data?.refresh_token || loginJson?.refresh_token;
if (!access || !refresh) {
return NextResponse.json(
{ error: `No tokens returned from Directus: ${loginText?.slice(0, 200) || "<empty>"}` },
{ status: 500 }
);
}
// Fetch user profile
const meRes = await fetch(`${BASE}/users/me`, {
headers: { Authorization: `Bearer ${access}`, Accept: "application/json" },
cache: "no-store",
});
const { json: meJson } = await jsonSafe(meRes);
if (!meRes.ok) {
return NextResponse.json(
{ error: meJson?.errors?.[0]?.message || "Failed to fetch user" },
{ status: 500 }
);
}
const user = {
id: String(meJson?.data?.id ?? ""),
email: String(meJson?.data?.email ?? ""),
username: String(meJson?.data?.username ?? ""),
};
let res = NextResponse.json({ ok: true, user });
res = setAuthCookies(res, { access_token: access, refresh_token: refresh }, user);
return res;
} catch (err: any) {
return NextResponse.json({ error: err?.message || "Login error" }, { status: 500 });
}
}