small build fixes to login route and cookies

This commit is contained in:
makearmy 2025-09-26 12:02:27 -04:00
parent 01c0d37d03
commit a6e52c5f67
2 changed files with 82 additions and 95 deletions

View file

@ -1,88 +1,54 @@
// app/app/api/auth/login/route.ts
import { NextRequest, NextResponse } from "next/server";
import { setAuthCookies } from "@/lib/auth-cookies";
// 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";
const BASE = process.env.DIRECTUS_URL!;
const ADMIN_TOKEN = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER!; // for username→email lookup
export const runtime = "nodejs";
type DirectusList<T> = { data: T[] };
type LoginResp = { data: { access_token: string; refresh_token: string; expires: number } };
type MeResp = { data: { id: string; email: string | null; username?: string | null } };
async function adminFetch<T=any>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
...init,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${ADMIN_TOKEN}`,
...(init?.headers || {}),
},
});
const text = await res.text();
const json = text ? JSON.parse(text) : null;
if (!res.ok) throw new Error(`Directus ${res.status}: ${text || res.statusText}`);
return (json ?? {}) as T;
function bad(msg: string, status = 400) {
return NextResponse.json({ ok: false, error: msg }, { status });
}
async function directusLogin(email: string, password: string): Promise<LoginResp["data"]> {
const res = await fetch(`${BASE}/auth/login`, {
method: "POST",
headers: { "Accept": "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const text = await res.text();
const json = text ? JSON.parse(text) : null;
if (!res.ok) throw new Error(`Login failed: ${text || res.statusText}`);
return json.data;
}
function isEmailLike(s: string) {
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(s);
}
export async function POST(req: NextRequest) {
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();
const identifier = String(body?.identifier || "").trim(); // username or email
const password = String(body?.password || "").trim();
if (!identifier || !password) {
return NextResponse.json({ error: "Missing identifier or password." }, { status: 400 });
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);
}
let email = identifier;
let username: string | undefined = undefined;
// 2) Login through Directus
const tokens = (await loginDirectus(email, password)) as TokenBundle;
if (!isEmailLike(identifier)) {
// lookup email by username (custom field on directus_users)
const q = `/users?limit=1&filter[username][_eq]=${encodeURIComponent(identifier)}&fields=id,email,username`;
const found = await adminFetch<DirectusList<{id:string;email:string|null;username:string|null}>>(q);
const user = found.data?.[0];
if (!user?.email) return NextResponse.json({ error: "User not found." }, { status: 404 });
email = user.email;
username = user.username || undefined;
}
// 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 tokens = await directusLogin(email, password);
// Fetch /users/me to confirm and obtain username (if email path)
const meRes = await fetch(`${BASE}/users/me?fields=id,email,username`, {
headers: { "Authorization": `Bearer ${tokens.access_token}`, "Accept": "application/json" },
});
const meText = await meRes.text();
const me: MeResp = meText ? JSON.parse(meText) : { data: { id: "", email: null, username: null } };
const user = {
id: String(me?.data?.id || ""),
email: me?.data?.email ?? null,
username: (me?.data?.username as string | null) ?? username ?? email.split("@")[0],
const user: PublicUser = {
id: String(userRow.id),
email: String(userRow.email || ""),
username: String(userRow.username || ""),
};
let res = NextResponse.json({ ok: true, user });
res = setAuthCookies(res, tokens, user);
// 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({ error: err?.message || "Login failed" }, { status: 401 });
return NextResponse.json({ ok: false, error: err?.message || "Login failed" }, { status: 401 });
}
}

View file

@ -1,32 +1,53 @@
// app/lib/auth-cookies.ts
import { NextResponse } from "next/server";
export const ACCESS_COOKIE = "ma_at";
export const REFRESH_COOKIE = "ma_rt";
export const USER_COOKIE = "ma_user"; // tiny JSON: {id, username, email?}
export type TokenBundle = {
access_token: string;
refresh_token?: string;
/** Directus returns seconds-until-expiration */
expires?: number;
};
export type PublicUser = {
id: string;
email: string;
username: string;
};
/**
* Mutates `res` in-place to set auth cookies.
* Keeps tokens HttpOnly; sets SameSite=Lax; Secure for HTTPS.
*/
export function setAuthCookies(
res: NextResponse,
tokens: { access_token: string; refresh_token: string; expires?: number },
user: { id: string; username: string; email?: string | null },
) {
const maxAge = tokens.expires ? Math.max(0, Math.floor((tokens.expires - Date.now()) / 1000)) : 60 * 60; // default 1h
res.cookies.set(ACCESS_COOKIE, tokens.access_token, {
httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge,
});
// keep refresh longer (7d)
res.cookies.set(REFRESH_COOKIE, tokens.refresh_token, {
httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge: 60 * 60 * 24 * 7,
});
res.cookies.set(USER_COOKIE, JSON.stringify(user), {
httpOnly: false, sameSite: "lax", secure: true, path: "/", maxAge,
});
return res;
}
tokens: TokenBundle,
_user?: PublicUser
): void {
const maxAge = typeof tokens.expires === "number" ? tokens.expires : 60 * 60 * 12; // 12h default
export function clearAuthCookies(res: NextResponse) {
res.cookies.set(ACCESS_COOKIE, "", { path: "/", maxAge: 0 });
res.cookies.set(REFRESH_COOKIE, "", { path: "/", maxAge: 0 });
res.cookies.set(USER_COOKIE, "", { path: "/", maxAge: 0 });
return res;
// Access token
if (tokens.access_token) {
res.cookies.set("ma_access", tokens.access_token, {
httpOnly: true,
sameSite: "lax",
secure: true,
path: "/",
maxAge,
});
}
// Refresh token (if present)
if (tokens.refresh_token) {
// Give it a longer lifetime (fallback 30 days) if Directus didnt specify one
const refreshMaxAge =
typeof tokens.expires === "number" ? tokens.expires * 4 : 60 * 60 * 24 * 30;
res.cookies.set("ma_refresh", tokens.refresh_token, {
httpOnly: true,
sameSite: "lax",
secure: true,
path: "/",
maxAge: refreshMaxAge,
});
}
}