54 lines
2.1 KiB
TypeScript
54 lines
2.1 KiB
TypeScript
// app/api/auth/login/route.ts
|
|
import { NextResponse } from "next/server";
|
|
import { emailForUsername, loginDirectus, directusAdminFetch } from "@/lib/directus";
|
|
import { setAuthCookies, type TokenBundle, type PublicUser } from "@/lib/auth-cookies";
|
|
|
|
export const runtime = "nodejs";
|
|
|
|
function bad(msg: string, status = 400) {
|
|
return NextResponse.json({ ok: false, error: msg }, { status });
|
|
}
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const body = await req.json().catch(() => ({}));
|
|
const identifier = String(body?.identifier || "").trim(); // username or email
|
|
const password = String(body?.password || "").trim();
|
|
|
|
if (!identifier) return bad("Missing identifier");
|
|
if (!password) return bad("Missing password");
|
|
|
|
// 1) Resolve email (Directus login requires email)
|
|
let email = identifier.includes("@") ? identifier : null;
|
|
if (!email) {
|
|
email = await emailForUsername(identifier);
|
|
if (!email) return bad("User not found", 404);
|
|
}
|
|
|
|
// 2) Login through Directus
|
|
const tokens = (await loginDirectus(email, password)) as TokenBundle;
|
|
|
|
// 3) Fetch minimal public user
|
|
const { data } = await directusAdminFetch<{ data: Array<{ id: string; email: string; username: string }> }>(
|
|
`/users?filter[email][_eq]=${encodeURIComponent(email)}&fields=id,email,username&limit=1`
|
|
);
|
|
const userRow = data?.[0];
|
|
if (!userRow) return bad("User not found after login", 404);
|
|
|
|
const user: PublicUser = {
|
|
id: String(userRow.id),
|
|
email: String(userRow.email || ""),
|
|
username: String(userRow.username || ""),
|
|
};
|
|
|
|
// 4) Build response and set cookies (mutates in-place)
|
|
const res = NextResponse.json<{ ok: boolean; user: PublicUser }>({
|
|
ok: true,
|
|
user,
|
|
});
|
|
setAuthCookies(res, tokens, user);
|
|
return res;
|
|
} catch (err: any) {
|
|
return NextResponse.json({ ok: false, error: err?.message || "Login failed" }, { status: 401 });
|
|
}
|
|
}
|