auth-cookies build error fix
This commit is contained in:
parent
7b2b185ed9
commit
514982d009
4 changed files with 213 additions and 133 deletions
|
|
@ -1,54 +1,72 @@
|
|||
// 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";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { setAuthCookies } from "@/lib/auth-cookies";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
const BASE = process.env.DIRECTUS_URL!;
|
||||
if (!BASE) console.warn("[auth/login] Missing DIRECTUS_URL");
|
||||
|
||||
function bad(msg: string, status = 400) {
|
||||
return NextResponse.json({ ok: false, error: msg }, { status });
|
||||
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: Request) {
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const identifier = String(body?.identifier || "").trim(); // username or email
|
||||
const password = String(body?.password || "").trim();
|
||||
const identity: string = (body.identity || body.usernameOrEmail || "").trim();
|
||||
const password: string = String(body.password || "");
|
||||
|
||||
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);
|
||||
if (!identity || !password) {
|
||||
return NextResponse.json({ error: "Missing identity or password" }, { status: 400 });
|
||||
}
|
||||
|
||||
// 2) Login through Directus
|
||||
const tokens = (await loginDirectus(email, password)) as TokenBundle;
|
||||
// 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 });
|
||||
}
|
||||
|
||||
// 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 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 }
|
||||
);
|
||||
}
|
||||
|
||||
const user: PublicUser = {
|
||||
id: String(userRow.id),
|
||||
email: String(userRow.email || ""),
|
||||
username: String(userRow.username || ""),
|
||||
// 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 ?? ""),
|
||||
};
|
||||
|
||||
// 4) Build response and set cookies (mutates in-place)
|
||||
const res = NextResponse.json<{ ok: boolean; user: PublicUser }>({
|
||||
ok: true,
|
||||
user,
|
||||
});
|
||||
setAuthCookies(res, tokens, user);
|
||||
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({ ok: false, error: err?.message || "Login failed" }, { status: 401 });
|
||||
return NextResponse.json({ error: err?.message || "Login error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue