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

70 lines
2.2 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";
import { loginDirectus } from "@/lib/directus";
2025-09-26 11:46:01 -04:00
2025-09-27 14:44:41 -04:00
export const runtime = "nodejs";
2025-09-26 11:46:01 -04:00
2025-09-27 14:44:41 -04:00
const secure = process.env.NODE_ENV === "production";
2025-09-26 11:46:01 -04:00
2025-09-27 14:44:41 -04:00
/**
* Accepts any of:
* - { identifier: string, password: string } // email OR username in `identifier`
2025-09-27 14:44:41 -04:00
* - { email: string, password: string }
* - { username: string, password: string }
*
* On success: sets HttpOnly "ma_at" cookie and returns { ok: true }.
*/
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 password = String(body?.password ?? "").trim();
const identifier = String(
body?.identifier ?? body?.email ?? body?.username ?? ""
).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
}
// Directus accepts username in the "email" field for /auth/login
const data = await loginDirectus(identifier, password);
2025-09-27 14:44:41 -04:00
const access =
data?.access_token ?? data?.data?.access_token ?? null;
const expiresSec =
data?.expires ?? data?.data?.expires ?? null;
2025-09-26 11:46:01 -04:00
if (!access) {
return NextResponse.json(
{ error: "Invalid response from auth provider" },
{ status: 502 }
);
2025-09-26 15:34:24 -04:00
}
2025-09-26 11:46:01 -04:00
2025-09-27 14:44:41 -04:00
const res = NextResponse.json({ ok: true });
// Max-Age from Directus if provided; else fallback to 8h
const maxAge =
typeof expiresSec === "number" ? Math.max(0, Math.floor(expiresSec)) : 60 * 60 * 8;
2025-09-27 14:44:41 -04:00
res.cookies.set({
name: "ma_at",
value: access,
httpOnly: true,
sameSite: "lax",
secure,
path: "/",
maxAge,
2025-09-26 15:34:24 -04:00
});
2025-09-26 11:46:01 -04:00
return res;
} catch (err: any) {
2025-09-27 14:44:41 -04:00
const message =
err?.response?.data?.error ||
err?.message ||
"Login failed";
const status = /unauth|invalid|credentials/i.test(message) ? 401 : 400;
return NextResponse.json({ error: message }, { status });
2025-09-26 11:46:01 -04:00
}
}