add reauth for account changes
This commit is contained in:
parent
3e4c6241f6
commit
b9c5c22f86
2 changed files with 128 additions and 0 deletions
65
app/api/auth/reconfirm/route.ts
Normal file
65
app/api/auth/reconfirm/route.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// 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 allowed)
|
||||
let 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”
|
||||
res.cookies.set({
|
||||
name: "ma_ra",
|
||||
value: "1",
|
||||
httpOnly: false,
|
||||
sameSite: "lax",
|
||||
secure,
|
||||
path: "/",
|
||||
maxAge: 5 * 60, // 5 minutes
|
||||
});
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
63
components/account/ConfirmIdentity.tsx
Normal file
63
components/account/ConfirmIdentity.tsx
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// components/account/ConfirmIdentity.tsx
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
|
||||
export default function ConfirmIdentity({
|
||||
defaultIdentifier,
|
||||
onSuccess,
|
||||
}: {
|
||||
defaultIdentifier: string; // prefill with username or email you show on the page
|
||||
onSuccess: () => void; // called after re-auth succeeds
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [identifier, setIdentifier] = useState(defaultIdentifier);
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
async function submit() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const res = await fetch("/api/auth/reconfirm", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ identifier, password }),
|
||||
});
|
||||
const j = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(j?.error || "Failed");
|
||||
setOpen(false);
|
||||
setPassword("");
|
||||
onSuccess(); // now do the sensitive call
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || "Re-auth failed");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* wherever you need the step-up, render a button that opens this */}
|
||||
<button className="btn" onClick={() => setOpen(true)}>Confirm it’s you</button>
|
||||
|
||||
{open && (
|
||||
<div className="fixed inset-0 bg-black/50 grid place-items-center">
|
||||
<div className="bg-card border rounded-lg p-4 w-full max-w-sm">
|
||||
<h3 className="font-semibold mb-2">Confirm it’s you</h3>
|
||||
<label className="block text-sm mb-1">Email or Username</label>
|
||||
<input className="input w-full mb-2" value={identifier} onChange={e=>setIdentifier(e.target.value)} />
|
||||
<label className="block text-sm mb-1">Password</label>
|
||||
<input className="input w-full mb-3" type="password" value={password} onChange={e=>setPassword(e.target.value)} />
|
||||
{err && <div className="text-red-600 text-sm mb-2">{err}</div>}
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button className="btn" onClick={()=>setOpen(false)} disabled={busy}>Cancel</button>
|
||||
<button className="btn-primary" onClick={submit} disabled={busy}>{busy ? "Checking…" : "Continue"}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue