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
@@ -1,12 +1,16 @@
"use client";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { AuthUser, TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
// Matches the backend's minimum gap between code sends.
const RESEND_COOLDOWN_SECONDS = 60;
export function LoginForm() {
const { login } = useAuth();
const { login, verifyTwoFactor, resendTwoFactor } = useAuth();
const searchParams = useSearchParams();
const raw = searchParams.get("redirect") || "";
const hasExplicitRedirect = raw.startsWith("/") && !raw.startsWith("//");
@@ -19,6 +23,25 @@ export function LoginForm() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Two-factor step — set once the password is accepted for an account with 2FA on.
const [challenge, setChallenge] = useState<TwoFactorChallenge | null>(null);
const [code, setCode] = useState("");
const [rememberDevice, setRememberDevice] = useState(false);
const [resendIn, setResendIn] = useState(0);
useEffect(() => {
if (resendIn <= 0) return;
const t = setTimeout(() => setResendIn((s) => s - 1), 1000);
return () => clearTimeout(t);
}, [resendIn]);
// Skip the generic /dashboard hop (which just redirects again once the role is known)
// and go straight to the role-specific dashboard, unless the caller asked for a specific
// page back (e.g. returning to a registration flow after login).
const goToDashboard = (loggedInUser: AuthUser) => {
window.location.href = hasExplicitRedirect ? redirectTo : `/dashboard/${loggedInUser.role || "user"}`;
};
const getErrorMessage = (err: any) => {
if (!err) return "Login failed";
@@ -45,12 +68,15 @@ export function LoginForm() {
setLoading(true);
try {
const loggedInUser = await login(email, password);
// Skip the generic /dashboard hop (which just redirects again once the role is known)
// and go straight to the role-specific dashboard, unless the caller asked for a specific
// page back (e.g. returning to a registration flow after login).
const target = hasExplicitRedirect ? redirectTo : `/dashboard/${loggedInUser.role || "user"}`;
window.location.href = target;
const result = await login(email, password);
if (isTwoFactorChallenge(result)) {
// Password was right, but the account has two-factor on — show the code step.
setChallenge(result);
setCode("");
setResendIn(RESEND_COOLDOWN_SECONDS);
return;
}
goToDashboard(result);
} catch (err: any) {
setError(getErrorMessage(err) || "Login failed. Please try again.");
} finally {
@@ -58,6 +84,102 @@ export function LoginForm() {
}
};
const onSubmitCode = async (e: React.FormEvent) => {
e.preventDefault();
if (!challenge) return;
setError(null);
setLoading(true);
try {
goToDashboard(await verifyTwoFactor(challenge.challengeId, code, rememberDevice));
} catch (err: any) {
setError(getErrorMessage(err) || "Verification failed. Please try again.");
} finally {
setLoading(false);
}
};
const onResend = async () => {
if (!challenge || resendIn > 0) return;
setError(null);
try {
setChallenge(await resendTwoFactor(challenge.challengeId));
setCode("");
setResendIn(RESEND_COOLDOWN_SECONDS);
} catch (err: any) {
setError(getErrorMessage(err) || "Couldn't send a new code. Please try again.");
}
};
const backToPassword = () => {
setChallenge(null);
setCode("");
setPassword("");
setError(null);
};
if (challenge) {
return (
<form onSubmit={onSubmitCode} className="space-y-4 max-w-sm w-full">
<div>
<h2 className="text-base font-semibold">Enter your verification code</h2>
<p className="text-sm text-gray-600 mt-1">
We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.
</p>
</div>
<div>
<label className="block text-sm font-medium mb-1">Verification code</label>
<input
type="text"
inputMode="numeric"
autoComplete="one-time-code"
maxLength={6}
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
className="w-full border rounded px-3 py-2 text-lg tracking-widest"
autoFocus
required
/>
</div>
<label className="flex items-start gap-2 text-sm text-gray-700 cursor-pointer">
<input
type="checkbox"
className="mt-0.5"
checked={rememberDevice}
onChange={(e) => setRememberDevice(e.target.checked)}
/>
<span>Trust this device for 30 days. Only tick this on a device that&apos;s yours.</span>
</label>
{error && <p className="text-sm text-red-600">{error}</p>}
<button
type="submit"
disabled={loading || code.length !== 6}
className="w-full bg-brand-600 hover:bg-brand-700 text-white rounded py-2 disabled:opacity-60"
>
{loading ? "Verifying..." : "Verify and log in"}
</button>
<div className="flex items-center justify-between text-xs">
<button type="button" onClick={backToPassword} className="text-brand-600 hover:underline">
Back to login
</button>
<button
type="button"
onClick={onResend}
disabled={resendIn > 0}
className="text-brand-600 hover:underline disabled:text-gray-400 disabled:no-underline"
>
{resendIn > 0 ? `Resend code in ${resendIn}s` : "Resend code"}
</button>
</div>
</form>
);
}
return (
<form onSubmit={onSubmit} className="space-y-4 max-w-sm w-full">
<div>