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

75 lines
3 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!;
const ADMIN_TOKEN = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || "";
async function findEmailForIdentifier(identifier: string): Promise<string | null> {
const id = (identifier || "").trim();
if (!id) return null;
// If it's an email, we're done.
if (id.includes("@")) return id;
// Otherwise look up by username using the admin/registration token.
if (!ADMIN_TOKEN) return null;
const res = await fetch(
`${BASE}/users?filter[username][_eq]=${encodeURIComponent(id)}&fields=id,email,username&limit=1`,
{ headers: { Authorization: `Bearer ${ADMIN_TOKEN}`, Accept: "application/json" } }
);
const json: any = await res.json().catch(() => null);
return json?.data?.[0]?.email ?? null;
}
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const identifier = (body?.identifier ?? body?.email ?? "").trim();
const password = body?.password ?? "";
if (!identifier || !password) {
return NextResponse.json({ error: "Missing credentials" }, { status: 400 });
}
const email = await findEmailForIdentifier(identifier);
if (!email) {
return NextResponse.json({ error: "Account not found" }, { status: 401 });
}
// Login to Directus
const loginRes = await fetch(`${BASE}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ email, password }),
});
const loginJson: any = await loginRes.json().catch(() => null);
if (!loginRes.ok) {
const msg = loginJson?.errors?.[0]?.message || loginRes.statusText;
return NextResponse.json({ error: msg }, { status: loginRes.status });
}
const tokens = loginJson?.data ?? loginJson ?? {};
const access = tokens.access_token;
const refresh = tokens.refresh_token;
if (!access) {
return NextResponse.json({ error: "Login failed (no token)" }, { status: 500 });
}
// Fetch user profile for the client
const meRes = await fetch(`${BASE}/users/me?fields=id,email,username`, {
headers: { Authorization: `Bearer ${access}`, Accept: "application/json" },
});
const meJson: any = await meRes.json().catch(() => null);
const user = (meJson?.data ?? meJson) || {};
let res = NextResponse.json({ ok: true, user });
// Persist auth cookies expected by the rest of the app
res = setAuthCookies(res as any, { access_token: access, refresh_token: refresh } as any, user);
return res;
} catch (err: any) {
return NextResponse.json({ error: err?.message || "Login error" }, { status: 500 });
}
}