Add optional two-factor authentication

Users can turn on 2FA from Profile & Security and receive a 6-digit
login code by email or WhatsApp, with a "trust this device for 30 days"
option. Admins can reset it for a locked-out user, and the self-service
kiosk handles the code step at setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 14:49:34 +02:00
co-authored by Claude Opus 5.5
parent c06e12b7d9
commit a21f12ae3c
19 changed files with 1530 additions and 51 deletions
@@ -6,16 +6,21 @@ import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { isValidZAPhone } from "@/lib/phone";
import { useDismissingState } from "@/hooks/useDismissingState";
import { User, Lock, ShieldAlert, Trash2, Clock, LogIn, KeyRound, RotateCcw } from "lucide-react";
import { TwoFactorChallenge, TwoFactorMethod } from "@/lib/auth";
import { User, Lock, ShieldAlert, ShieldCheck, ShieldOff, Trash2, Clock, LogIn, KeyRound, RotateCcw } from "lucide-react";
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset"; device: string | null; createdAt: string };
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | null) => string; icon: typeof LogIn }> = {
login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn },
password_changed: { label: () => "Password changed", icon: KeyRound },
password_reset: { label: () => "Password reset via email link", icon: RotateCcw },
two_factor_enabled: { label: () => "Two-factor authentication turned on", icon: ShieldCheck },
two_factor_disabled: { label: () => "Two-factor authentication turned off", icon: ShieldOff },
};
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp" };
export default function UserProfilePage() {
const { user, token, logout, updateToken } = useAuth();
const router = useRouter();
@@ -152,6 +157,102 @@ export default function UserProfilePage() {
useEffect(() => { loadActivity(); }, [token]);
// ── Two-factor authentication ─────────────────────────────────────────────
// Mirrors the saved account state locally: the auth context's `user` is only
// loaded once per page load, so it wouldn't reflect a change made here.
const [tfEnabled, setTfEnabled] = useState(false);
const [tfMethod, setTfMethod] = useState<TwoFactorMethod>("email");
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable">("idle");
const [tfPassword, setTfPassword] = useState("");
const [tfCode, setTfCode] = useState("");
const [tfChallenge, setTfChallenge] = useState<TwoFactorChallenge | null>(null);
const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
const [tfBusy, setTfBusy] = useState(false);
// WhatsApp codes need the number that's actually saved, not one still being typed.
const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || "");
useEffect(() => {
if (user) {
setTfEnabled(!!user.twoFactorEnabled);
setTfMethod(user.twoFactorMethod || "email");
}
}, [user]);
const resetTwoFactorForm = () => {
setTfStep("idle");
setTfPassword("");
setTfCode("");
setTfChallenge(null);
};
const startEnableTwoFactor = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
setTfBusy(true);
setTfMsg(null);
try {
const res = await apiFetch<TwoFactorChallenge>("/api/users/2fa/enable", {
method: "POST",
authToken: token,
body: { method: tfMethod, password: tfPassword },
});
setTfChallenge(res);
setTfCode("");
setTfPassword("");
setTfStep("code");
} catch (e: any) {
setTfMsg({ type: "err", text: e?.message || "Failed to send a verification code." });
} finally {
setTfBusy(false);
}
};
const confirmEnableTwoFactor = async (e: React.FormEvent) => {
e.preventDefault();
if (!token || !tfChallenge) return;
setTfBusy(true);
setTfMsg(null);
try {
const res = await apiFetch<{ twoFactorMethod: TwoFactorMethod }>("/api/users/2fa/confirm", {
method: "POST",
authToken: token,
body: { challengeId: tfChallenge.challengeId, code: tfCode },
});
setTfEnabled(true);
setTfMethod(res.twoFactorMethod);
resetTwoFactorForm();
setTfMsg({ type: "ok", text: "Two-factor authentication is on." });
loadActivity();
} catch (e: any) {
setTfMsg({ type: "err", text: e?.message || "Failed to verify the code." });
} finally {
setTfBusy(false);
}
};
const disableTwoFactor = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
setTfBusy(true);
setTfMsg(null);
try {
await apiFetch("/api/users/2fa/disable", {
method: "POST",
authToken: token,
body: { password: tfPassword },
});
setTfEnabled(false);
resetTwoFactorForm();
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
loadActivity();
} catch (e: any) {
setTfMsg({ type: "err", text: e?.message || "Failed to turn off two-factor authentication." });
} finally {
setTfBusy(false);
}
};
// ── Account closure ───────────────────────────────────────────────────────
const [closeStep, setCloseStep] = useState<"idle" | "confirm">("idle");
const [deleteData, setDeleteData] = useState(false);
@@ -299,6 +400,94 @@ export default function UserProfilePage() {
</form>
</section>
{/* ── Two-factor authentication ────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={ShieldCheck} title="Two-factor authentication" />
{tfEnabled ? (
<>
<p className="text-sm text-gray-500 mb-4">
<span className="font-medium text-green-700">On.</span> When you log in we send a 6-digit code by{" "}
{TWO_FACTOR_METHOD_LABEL[tfMethod]}. Devices you&apos;ve chosen to trust skip the code for 30 days.
</p>
{tfStep !== "disable" ? (
<button
onClick={() => { setTfStep("disable"); setTfPassword(""); setTfMsg(null); }}
className="px-4 py-2 rounded-lg border border-gray-300 text-gray-700 text-sm font-medium hover:bg-gray-50"
>
Turn off…
</button>
) : (
<form onSubmit={disableTwoFactor} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Confirm with your password</label>
<input type="password" className={inputCls} value={tfPassword} onChange={e => setTfPassword(e.target.value)} required autoComplete="current-password" />
</div>
<div className="flex gap-3">
<button type="button" onClick={resetTwoFactorForm} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">
Cancel
</button>
<button type="submit" disabled={tfBusy || !tfPassword} className="px-4 py-2 rounded-lg bg-amber-500 text-white text-sm font-medium hover:bg-amber-600 disabled:opacity-50">
{tfBusy ? "Turning off…" : "Turn off two-factor"}
</button>
</div>
</form>
)}
</>
) : tfStep === "code" && tfChallenge ? (
<form onSubmit={confirmEnableTwoFactor} className="space-y-4">
<p className="text-sm text-gray-500">
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. Enter it to finish turning on two-factor authentication.
</p>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Verification code</label>
<input
type="text"
inputMode="numeric"
autoComplete="one-time-code"
maxLength={6}
className={`${inputCls} tracking-widest`}
value={tfCode}
onChange={e => setTfCode(e.target.value.replace(/\D/g, ""))}
required
/>
</div>
<div className="flex gap-3">
<button type="button" onClick={resetTwoFactorForm} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">
Cancel
</button>
<button type="submit" disabled={tfBusy || tfCode.length !== 6} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{tfBusy ? "Verifying…" : "Turn on two-factor"}
</button>
</div>
</form>
) : (
<form onSubmit={startEnableTwoFactor} className="space-y-4">
<p className="text-sm text-gray-500">
Add a second step to logging in: after your password, we send a 6-digit code that you need to enter.
</p>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Send my codes by</label>
<select className={inputCls} value={tfMethod} onChange={e => setTfMethod(e.target.value as TwoFactorMethod)}>
<option value="email">Email</option>
{canWhatsAppCodes && <option value="whatsapp">WhatsApp</option>}
</select>
{!canWhatsAppCodes && (
<p className="mt-1 text-xs text-gray-500">Save a valid phone number on your profile to receive codes by WhatsApp.</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Confirm with your password</label>
<input type="password" className={inputCls} value={tfPassword} onChange={e => setTfPassword(e.target.value)} required autoComplete="current-password" />
</div>
<button type="submit" disabled={tfBusy || !tfPassword} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{tfBusy ? "Sending code…" : "Send verification code"}
</button>
</form>
)}
{tfMsg && <Alert msg={tfMsg} />}
</section>
{/* ── Security ─────────────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={ShieldAlert} title="Security" tone="amber" />