This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/components/auth/LoginForm.tsx
T
joshuaandClaude Opus 5.5 e52bf67015 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>
2026-10-08 14:49:34 +02:00

271 lines
9.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
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, verifyTwoFactor, resendTwoFactor } = useAuth();
const searchParams = useSearchParams();
const raw = searchParams.get("redirect") || "";
const hasExplicitRedirect = raw.startsWith("/") && !raw.startsWith("//");
const redirectTo = hasExplicitRedirect ? raw : "/dashboard";
const registerHref = redirectTo !== "/dashboard" ? `/register?redirect=${encodeURIComponent(redirectTo)}` : "/register";
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
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";
// If it's already a normal Error
if (err.message && typeof err.message === "string") {
// Handle case where message is accidentally JSON string
try {
const parsed = JSON.parse(err.message);
return parsed.message || err.message;
} catch {
return err.message;
}
}
// If API response object was thrown directly
if (err.message) return err.message;
return "Login failed";
};
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
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 {
setLoading(false);
}
};
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>
<label className="block text-sm font-medium mb-1">Email or phone</label>
<input
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full border rounded px-3 py-2"
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Password</label>
<div className="relative">
<input
type={showPassword ? "text" : "password"}
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full border rounded px-3 py-2 pr-20"
required
/>
<button
type="button"
onClick={() => setShowPassword((s) => !s)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-sm text-brand-600"
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? "Hide" : "Show"}
</button>
</div>
<div className="mt-1">
<a
href="/forgot-password"
className="text-xs text-brand-600 hover:underline"
>
Forgot your password?
</a>
</div>
<div className="mt-1">
<a
href={registerHref}
className="text-xs text-brand-600 hover:underline"
>
Don't have an account? Sign up here.
</a>
</div>
</div>
{error && (
<div className="text-sm text-red-600">
<p>{error}</p>
{error.toLowerCase().includes('not yet active') && (
<p className="mt-1 text-gray-600">Check your inbox for an activation email. If you didn&apos;t receive it, try logging in again to resend it.</p>
)}
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full bg-brand-600 hover:bg-brand-700 text-white rounded py-2 disabled:opacity-60"
>
{loading ? "Logging in..." : "Login"}
</button>
<p className="text-xs text-gray-500 text-center mt-3">
By signing in, you acknowledge that you’ve read and agree to our{" "}
<Link
href="/legal/terms"
target="_blank"
className="text-brand-600 hover:underline"
>
Terms of Use
</Link>{" "}
and{" "}
<Link
href="/legal/privacy"
target="_blank"
className="text-brand-600 hover:underline"
>
Privacy Policy
</Link>.
</p>
</form>
);
}