sign in with username only restored

This commit is contained in:
makearmy 2025-09-27 14:44:41 -04:00
parent bce0c5063b
commit c7511b98fc
2 changed files with 68 additions and 65 deletions

View file

@ -1,75 +1,79 @@
// app/api/auth/login/route.ts // app/api/auth/login/route.ts
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { setAuthCookies } from "@/lib/auth-cookies"; import { emailForUsername, loginDirectus } from "@/lib/directus";
const BASE = process.env.DIRECTUS_URL!; export const runtime = "nodejs";
const ADMIN_TOKEN = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || "";
async function findEmailForIdentifier(identifier: string): Promise<string | null> { const secure = process.env.NODE_ENV === "production";
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;
}
/**
* Accepts any of:
* - { identifier: string, password: string } // email or username in `identifier`
* - { email: string, password: string }
* - { username: string, password: string }
*
* On success: sets HttpOnly "ma_at" cookie and returns { ok: true }.
*/
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
try { try {
const body = await req.json(); const body = await req.json().catch(() => ({} as any));
const identifier = (body?.identifier ?? body?.email ?? "").trim(); const { password } = body as { identifier?: string; email?: string; username?: string; password?: string };
const password = body?.password ?? "";
let identifier = (body?.identifier ?? body?.email ?? body?.username ?? "").trim();
if (!identifier || !password) { if (!identifier || !password) {
return NextResponse.json({ error: "Missing credentials" }, { status: 400 }); return NextResponse.json({ error: "Missing credentials" }, { status: 400 });
} }
const email = await findEmailForIdentifier(identifier); // Resolve to an email for Directus login:
// - If identifier looks like an email, use it directly.
// - Otherwise treat it as a username and look up the email.
let email = identifier.includes("@") ? identifier : null;
if (!email) { if (!email) {
return NextResponse.json({ error: "Account not found" }, { status: 401 }); email = await emailForUsername(identifier);
if (!email) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
} }
// Login to Directus // Login against Directus; helper returns { access_token, refresh_token?, expires? } in .data or root
const loginRes = await fetch(`${BASE}/auth/login`, { const data = await loginDirectus(email, password);
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" }, const access =
body: JSON.stringify({ email, password }), data?.access_token ?? data?.data?.access_token ?? null;
}); const expiresSec =
const loginJson: any = await loginRes.json().catch(() => null); data?.expires ?? data?.data?.expires ?? 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) { if (!access) {
return NextResponse.json({ error: "Login failed (no token)" }, { status: 500 }); return NextResponse.json({ error: "Invalid response from auth provider" }, { status: 502 });
} }
// Fetch user profile for the client const res = NextResponse.json({ ok: true });
const meRes = await fetch(`${BASE}/users/me?fields=id,email,username`, {
headers: { Authorization: `Bearer ${access}`, Accept: "application/json" }, // Set access token cookie
}); // - HttpOnly so JS can't read it
const meJson: any = await meRes.json().catch(() => null); // - SameSite=Lax to allow normal navigation
const user = (meJson?.data ?? meJson) || {}; // - Secure in production
// - Max-Age from Directus if provided; else fallback to 8h
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,
});
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; return res;
} catch (err: any) { } catch (err: any) {
return NextResponse.json({ error: err?.message || "Login error" }, { status: 500 }); const message =
err?.response?.data?.error ||
err?.message ||
"Login failed";
// Return 401 for auth problems; 400 for others
const status = /unauth|invalid|credentials/i.test(message) ? 401 : 400;
return NextResponse.json({ error: message }, { status });
} }
} }

View file

@ -8,7 +8,7 @@ type Props = { nextPath?: string };
export default function SignIn({ nextPath = "/portal" }: Props) { export default function SignIn({ nextPath = "/portal" }: Props) {
const router = useRouter(); const router = useRouter();
const [email, setEmail] = useState(""); const [identifier, setIdentifier] = useState(""); // email OR username
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -24,7 +24,7 @@ export default function SignIn({ nextPath = "/portal" }: Props) {
method: "POST", method: "POST",
credentials: "include", credentials: "include",
headers: { "Content-Type": "application/json", Accept: "application/json" }, headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ email, password }), body: JSON.stringify({ identifier, password }),
}); });
const txt = await res.text(); const txt = await res.text();
@ -36,30 +36,31 @@ export default function SignIn({ nextPath = "/portal" }: Props) {
throw new Error(message); throw new Error(message);
} }
router.replace(nextPath); // ALWAYS /portal // Always land on the portal in this new flow
router.replace(nextPath);
router.refresh(); router.refresh();
} catch (e: any) { } catch (e: any) {
setErr(e?.message || "Unable to sign in."); setErr(e?.message || "Unable to sign in.");
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [email, password, nextPath, router]); }, [identifier, password, nextPath, router]);
return ( return (
<div className="mx-auto max-w-md rounded-lg border p-6"> <div className="mx-auto max-w-md rounded-lg border p-6">
<h1 className="mb-1 text-2xl font-semibold">Sign In</h1> <h1 className="mb-1 text-2xl font-semibold">Sign In</h1>
<p className="mb-6 text-sm opacity-70">Welcome back! Enter your credentials to continue.</p> <p className="mb-6 text-sm opacity-70">Use your email <em>or</em> username with your password.</p>
<form className="space-y-4" onSubmit={onSubmit}> <form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-1"> <div className="space-y-1">
<label className="text-sm font-medium">Email</label> <label className="text-sm font-medium">Email or Username</label>
<input <input
type="email" type="text"
autoComplete="email" autoComplete="username"
className="w-full rounded-md border px-3 py-2" className="w-full rounded-md border px-3 py-2"
placeholder="you@example.com" placeholder="you@example.com or your-handle"
value={email} value={identifier}
onChange={(e) => setEmail(e.currentTarget.value)} onChange={(e) => setIdentifier(e.currentTarget.value)}
required required
/> />
</div> </div>
@ -103,9 +104,7 @@ export default function SignIn({ nextPath = "/portal" }: Props) {
<div className="mt-4 text-center text-sm"> <div className="mt-4 text-center text-sm">
<span className="opacity-70">New here?</span>{" "} <span className="opacity-70">New here?</span>{" "}
<a className="underline" href={"/auth/sign-up"}> <a className="underline" href={"/auth/sign-up"}>Create an account</a>
Create an account
</a>
</div> </div>
</div> </div>
); );