66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
// app/api/auth/reconfirm/route.ts
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
import { emailForUsername, loginDirectus } from "@/lib/directus";
|
|
|
|
export const runtime = "nodejs";
|
|
const secure = process.env.NODE_ENV === "production";
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const body = await req.json().catch(() => ({} as any));
|
|
const identifier = String(body?.identifier ?? "").trim();
|
|
const password = String(body?.password ?? "").trim();
|
|
|
|
if (!identifier || !password) {
|
|
return NextResponse.json({ error: "Missing credentials" }, { status: 400 });
|
|
}
|
|
|
|
// Resolve identifier -> email (username or email accepted)
|
|
const email = identifier.includes("@") ? identifier : await emailForUsername(identifier);
|
|
if (!email) return NextResponse.json({ error: "User not found" }, { status: 404 });
|
|
|
|
const auth = await loginDirectus(email, password);
|
|
const access = auth?.access_token ?? auth?.data?.access_token;
|
|
const expiresSec = auth?.expires ?? auth?.data?.expires;
|
|
|
|
if (!access) {
|
|
return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
|
|
}
|
|
|
|
const res = NextResponse.json({ ok: true });
|
|
|
|
// Refresh the access token cookie
|
|
const maxAge =
|
|
typeof expiresSec === "number" ? Math.max(0, Math.floor(expiresSec)) : 60 * 60 * 8;
|
|
res.cookies.set({
|
|
name: "ma_at",
|
|
value: access,
|
|
httpOnly: true,
|
|
sameSite: "lax",
|
|
secure,
|
|
path: "/",
|
|
maxAge,
|
|
});
|
|
|
|
// Short-lived client-visible flag: “recently authenticated” (5 minutes)
|
|
res.cookies.set({
|
|
name: "ma_ra",
|
|
value: "1",
|
|
httpOnly: false,
|
|
sameSite: "lax",
|
|
secure,
|
|
path: "/",
|
|
maxAge: 5 * 60,
|
|
});
|
|
|
|
return res;
|
|
} catch (err: any) {
|
|
const msg =
|
|
err?.response?.data?.errors?.[0]?.message ||
|
|
err?.response?.data?.error ||
|
|
err?.message ||
|
|
"Re-auth failed";
|
|
const status = /invalid|credential/i.test(msg) ? 401 : 400;
|
|
return NextResponse.json({ error: msg }, { status });
|
|
}
|
|
}
|