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

83 lines
2.9 KiB
TypeScript
Raw Normal View History

// app/api/auth/login/route.ts
2025-09-26 15:34:24 -04:00
import { NextRequest, NextResponse } from "next/server";
2025-09-30 01:14:10 -04:00
import { emailForUsername, loginDirectus } from "@/lib/directus";
2025-09-26 11:46:01 -04:00
2025-09-27 14:44:41 -04:00
export const runtime = "nodejs";
const secure = process.env.NODE_ENV === "production";
2025-09-26 11:46:01 -04:00
2025-09-26 15:34:24 -04:00
export async function POST(req: NextRequest) {
2025-09-26 11:46:01 -04:00
try {
2025-09-27 14:44:41 -04:00
const body = await req.json().catch(() => ({} as any));
const identifier =
String(body?.identifier ?? body?.email ?? body?.username ?? "").trim();
const password = String(body?.password ?? "").trim();
2025-09-26 11:46:01 -04:00
if (!identifier || !password) {
return NextResponse.json({ error: "Missing credentials" }, { status: 400 });
2025-09-26 11:46:01 -04:00
}
// 1) Try Directus directly with the identifier (email OR username)
// Directus expects the field name "email" for both.
const tryIds: string[] = [identifier];
// 2) Fallback: if it doesnt look like an email, try the canonical email (if any)
if (!identifier.includes("@")) {
try {
const em = await emailForUsername(identifier); // returns string|null
if (em && em !== identifier) tryIds.push(em);
} catch {
// ignore lookup errors, we'll just rely on the first attempt
2025-09-30 01:14:10 -04:00
}
}
let tokens: any = null;
let lastErr: any = null;
for (const id of tryIds) {
try {
tokens = await loginDirectus(id, password); // { access_token, refresh_token, expires? }
if (tokens) break;
} catch (e) {
lastErr = e;
}
}
2025-09-26 11:46:01 -04:00
if (!tokens?.access_token) {
const msg =
lastErr?.response?.data?.errors?.[0]?.message ||
lastErr?.response?.data?.error ||
lastErr?.message ||
"Invalid credentials.";
return NextResponse.json({ error: msg }, { status: 401 });
2025-09-26 15:34:24 -04:00
}
2025-09-26 11:46:01 -04:00
// Set HttpOnly cookies for your middleware
const maxAge = 60 * 60; // 1h
2025-09-27 14:44:41 -04:00
const res = NextResponse.json({ ok: true });
res.cookies.set("ma_at", tokens.access_token, {
path: "/",
2025-09-27 14:44:41 -04:00
httpOnly: true,
sameSite: "lax",
secure,
maxAge,
2025-09-26 15:34:24 -04:00
});
if (tokens.refresh_token) {
res.cookies.set("ma_rt", tokens.refresh_token, {
path: "/",
httpOnly: true,
sameSite: "lax",
secure,
maxAge: 60 * 60 * 24 * 30, // 30d
});
}
2025-09-26 11:46:01 -04:00
return res;
} catch (err: any) {
2025-09-27 14:44:41 -04:00
const message =
2025-09-30 01:14:10 -04:00
err?.response?.data?.errors?.[0]?.message ||
2025-09-27 14:44:41 -04:00
err?.response?.data?.error ||
err?.message ||
"Login failed";
2025-09-30 01:14:10 -04:00
const status = /unauth|invalid|credential/i.test(message) ? 401 : 400;
2025-09-27 14:44:41 -04:00
return NextResponse.json({ error: message }, { status });
2025-09-26 11:46:01 -04:00
}
}