Auth Flow
FreeSign in, two-factor code and password reset in one card: inline validation, a shake and selected field on a wrong password, caps-lock warning, attempt lockout with countdown, paste-aware OTP input and resend timer.
Hide codecomponents/blocks/auth-flow.tsx
"use client";
import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion, useAnimate, useReducedMotion } from "motion/react";
import { AlertCircle, ArrowLeft, Check, Eye, EyeOff, KeyRound, Loader2, Mail, ShieldCheck } from "lucide-react";
import { cn } from "@/lib/utils";
type Step = "signin" | "otp" | "forgot" | "sent" | "newpass" | "done";
const DEMO_PASSWORD = "viewport123";
const DEMO_CODE = "424242";
const LOCKED_MESSAGE = "Too many attempts. Wait a moment, or reset your password.";
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const field =
"h-10 w-full rounded-md border bg-background px-3 text-sm outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground/70 focus:border-foreground/40 focus:ring-[3px] focus:ring-ring/20 aria-[invalid=true]:border-red-500/70 aria-[invalid=true]:focus:ring-red-500/20";
const primary =
"relative inline-flex h-10 w-full items-center justify-center gap-2 overflow-hidden rounded-md bg-foreground text-sm font-medium text-background shadow-[inset_0_1px_0_rgb(255_255_255/0.18),0_1px_2px_rgb(0_0_0/0.24),0_6px_14px_-8px_rgb(0_0_0/0.5)] outline-none transition-[background-color,scale,box-shadow] hover:bg-foreground/90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background active:scale-[0.985] active:shadow-[inset_0_1px_2px_rgb(0_0_0/0.3)] disabled:pointer-events-none disabled:opacity-60";
const link = "rounded-sm font-medium text-foreground underline-offset-4 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring";
function FieldError({ id, children }: { id: string; children?: string }) {
return (
<AnimatePresence initial={false}>
{children ? (
<motion.p
id={id}
initial={{ opacity: 0, height: 0, y: -4 }}
animate={{ opacity: 1, height: "auto", y: 0 }}
exit={{ opacity: 0, height: 0, y: -4 }}
transition={{ duration: 0.18 }}
className="flex items-center gap-1.5 overflow-hidden pt-1.5 text-xs text-red-600 dark:text-red-400"
>
<AlertCircle className="size-3.5 shrink-0" aria-hidden />
{children}
</motion.p>
) : null}
</AnimatePresence>
);
}
type Lockout = { attempts: number; until: number };
function SignIn({
onDone,
onForgot,
email,
setEmail,
lockout,
setLockout,
expected,
}: {
onDone: () => void;
onForgot: () => void;
email: string;
setEmail: (v: string) => void;
lockout: Lockout;
setLockout: (l: Lockout) => void;
expected: string;
}) {
const reduce = useReducedMotion();
const [scope, animate] = useAnimate<HTMLFormElement>();
const pwRef = useRef<HTMLInputElement>(null);
const [password, setPassword] = useState("");
const [show, setShow] = useState(false);
const [caps, setCaps] = useState(false);
const [lockedFor, setLockedFor] = useState(() => Math.max(0, Math.ceil((lockout.until - Date.now()) / 1000)));
const [errors, setErrors] = useState<{ email?: string; password?: string; form?: string }>(() =>
lockedFor > 0 ? { form: LOCKED_MESSAGE } : {},
);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (lockedFor <= 0) return;
const id = setTimeout(() => setLockedFor((s) => s - 1), 1000);
return () => clearTimeout(id);
}, [lockedFor]);
const shake = () => {
if (!reduce && scope.current) animate(scope.current, { x: [0, -8, 7, -5, 3, 0] }, { duration: 0.42, ease: "easeOut" });
};
async function submit(e: React.FormEvent) {
e.preventDefault();
const next: typeof errors = {};
if (!email.trim()) next.email = "Enter your email.";
else if (!EMAIL.test(email)) next.email = "That doesn't look like an email address.";
if (!password) next.password = "Enter your password.";
setErrors(next);
if (next.email || next.password) {
shake();
(scope.current?.querySelector(`[name="${next.email ? "email" : "password"}"]`) as HTMLInputElement | null)?.focus();
return;
}
setBusy(true);
await wait(700);
setBusy(false);
if (password !== expected) {
const n = lockout.attempts + 1;
if (n >= 3) {
setLockout({ attempts: n, until: Date.now() + 15_000 });
setLockedFor(15);
setErrors({ form: LOCKED_MESSAGE });
} else {
setLockout({ attempts: n, until: 0 });
setErrors({ password: "Incorrect password.", form: n === 2 ? "One more wrong attempt will pause sign-in briefly." : undefined });
}
shake();
pwRef.current?.select();
pwRef.current?.focus();
return;
}
setLockout({ attempts: 0, until: 0 });
onDone();
}
const locked = lockedFor > 0;
return (
<form ref={scope} onSubmit={submit} noValidate className="space-y-4">
<AnimatePresence initial={false}>
{errors.form ? (
<motion.div
role="alert"
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
className="overflow-hidden"
>
<div className="flex gap-2 rounded-md border border-red-500/25 bg-red-500/[0.06] px-3 py-2.5 text-[13px] text-red-700 dark:text-red-300">
<AlertCircle className="mt-px size-4 shrink-0" aria-hidden />
<span>
{errors.form}
{locked ? <span className="ml-1 tabular-nums text-red-600/80 dark:text-red-300/80">({lockedFor}s)</span> : null}
</span>
</div>
</motion.div>
) : null}
</AnimatePresence>
<div>
<label htmlFor="af-email" className="mb-1.5 block text-[13px] font-medium">Email</label>
<input
id="af-email"
name="email"
type="email"
autoComplete="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
if (errors.email) setErrors((x) => ({ ...x, email: undefined }));
}}
placeholder="you@company.com"
aria-invalid={!!errors.email}
aria-describedby={errors.email ? "af-email-error" : undefined}
className={cn(field, "border-border")}
/>
<FieldError id="af-email-error">{errors.email}</FieldError>
</div>
<div>
<div className="mb-1.5 flex items-baseline justify-between">
<label htmlFor="af-password" className="text-[13px] font-medium">Password</label>
<button type="button" onClick={onForgot} className={cn(link, "text-xs text-muted-foreground hover:text-foreground")}>Forgot password?</button>
</div>
<div className="relative">
<input
ref={pwRef}
id="af-password"
name="password"
type={show ? "text" : "password"}
autoComplete="current-password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
if (errors.password) setErrors((x) => ({ ...x, password: undefined }));
}}
onKeyDown={(e) => setCaps(e.getModifierState("CapsLock"))}
onKeyUp={(e) => setCaps(e.getModifierState("CapsLock"))}
onBlur={() => setCaps(false)}
aria-invalid={!!errors.password}
aria-describedby={errors.password ? "af-password-error" : caps ? "af-caps" : undefined}
className={cn(field, "border-border pr-10")}
/>
<button
type="button"
onClick={() => setShow((v) => !v)}
aria-label={show ? "Hide password" : "Show password"}
aria-pressed={show}
className="absolute inset-y-0 right-1 my-auto grid size-8 place-items-center rounded-md text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
{show ? <EyeOff className="size-4" aria-hidden /> : <Eye className="size-4" aria-hidden />}
</button>
</div>
<FieldError id="af-password-error">{errors.password}</FieldError>
<AnimatePresence initial={false}>
{caps && !errors.password ? (
<motion.p id="af-caps" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} className="overflow-hidden pt-1.5 text-xs text-amber-600 dark:text-amber-400">
Caps Lock is on.
</motion.p>
) : null}
</AnimatePresence>
</div>
<button type="submit" disabled={busy || locked} className={primary}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span key={busy ? "busy" : locked ? "locked" : "idle"} initial={{ y: 12, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: -12, opacity: 0 }} transition={{ duration: 0.18 }} className="inline-flex items-center gap-2">
{busy ? <><Loader2 className="size-4 animate-spin" aria-hidden />Signing in…</> : locked ? <>Try again in {lockedFor}s</> : "Sign in"}
</motion.span>
</AnimatePresence>
</button>
</form>
);
}
function CodeInput({ onComplete, error, disabled }: { onComplete: (code: string) => void; error: boolean; disabled: boolean }) {
const [digits, setDigits] = useState<string[]>(Array(6).fill(""));
const refs = useRef<(HTMLInputElement | null)[]>([]);
const commit = (next: string[]) => {
setDigits(next);
if (next.every(Boolean)) onComplete(next.join(""));
};
const fill = (start: number, text: string) => {
const chars = text.replace(/\D/g, "").slice(0, 6 - start).split("");
if (!chars.length) return;
const next = [...digits];
chars.forEach((c, i) => (next[start + i] = c));
refs.current[Math.min(start + chars.length, 5)]?.focus();
commit(next);
};
return (
<div className="flex justify-between gap-1.5 sm:gap-2" role="group" aria-label="6-digit code">
{digits.map((d, i) => (
<motion.input
key={i}
ref={(el) => {
refs.current[i] = el;
}}
value={d}
disabled={disabled}
inputMode="numeric"
autoComplete={i === 0 ? "one-time-code" : "off"}
aria-label={`Digit ${i + 1}`}
aria-invalid={error}
maxLength={1}
autoFocus={i === 0}
animate={d ? { scale: [0.92, 1] } : { scale: 1 }}
transition={{ duration: 0.16 }}
onFocus={(e) => e.target.select()}
onPaste={(e) => {
e.preventDefault();
fill(i, e.clipboardData.getData("text"));
}}
onChange={(e) => {
const v = e.target.value.replace(/\D/g, "");
if (v.length > 1) return fill(i, v);
const next = [...digits];
next[i] = v;
if (v && i < 5) refs.current[i + 1]?.focus();
commit(next);
}}
onKeyDown={(e) => {
if (e.key === "Backspace" && !digits[i] && i > 0) {
const next = [...digits];
next[i - 1] = "";
setDigits(next);
refs.current[i - 1]?.focus();
e.preventDefault();
}
if (e.key === "ArrowLeft" && i > 0) refs.current[i - 1]?.focus();
if (e.key === "ArrowRight" && i < 5) refs.current[i + 1]?.focus();
}}
className={cn(
"aspect-[5/6] w-full min-w-0 rounded-md border bg-background text-center font-mono text-lg font-medium tabular-nums outline-none transition-[border-color,box-shadow] focus:border-foreground/40 focus:ring-[3px] focus:ring-ring/20 disabled:opacity-60 sm:text-xl",
error ? "border-red-500/70" : d ? "border-foreground/25" : "border-border",
)}
/>
))}
</div>
);
}
function Otp({ email, onDone, onBack }: { email: string; onDone: () => void; onBack: () => void }) {
const reduce = useReducedMotion();
const [scope, animate] = useAnimate<HTMLDivElement>();
const [error, setError] = useState<string>();
const [busy, setBusy] = useState(false);
const [resendIn, setResendIn] = useState(30);
const [resent, setResent] = useState(false);
const [round, setRound] = useState(0);
useEffect(() => {
if (resendIn <= 0) return;
const id = setTimeout(() => setResendIn((s) => s - 1), 1000);
return () => clearTimeout(id);
}, [resendIn]);
async function check(code: string) {
setError(undefined);
setBusy(true);
await wait(600);
setBusy(false);
if (code !== DEMO_CODE) {
setError("That code isn't right. Check the latest email and try again.");
setRound((r) => r + 1);
if (!reduce && scope.current) animate(scope.current, { x: [0, -8, 7, -5, 3, 0] }, { duration: 0.42 });
return;
}
onDone();
}
return (
<div className="space-y-5">
<div ref={scope}>
<CodeInput key={round} onComplete={check} error={!!error && round > 0} disabled={busy} />
</div>
<div aria-live="polite" className="min-h-5 text-center text-xs">
{busy ? (
<span className="inline-flex items-center gap-1.5 text-muted-foreground"><Loader2 className="size-3.5 animate-spin" aria-hidden />Verifying…</span>
) : error ? (
<span className="text-red-600 dark:text-red-400">{error}</span>
) : resent ? (
<span className="text-muted-foreground">New code sent to {email || "your inbox"}.</span>
) : null}
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<button type="button" onClick={onBack} className={cn(link, "inline-flex items-center gap-1 text-muted-foreground hover:text-foreground")}>
<ArrowLeft className="size-3.5" aria-hidden />Back
</button>
{resendIn > 0 ? (
<span className="tabular-nums">Resend in 0:{String(resendIn).padStart(2, "0")}</span>
) : (
<button
type="button"
onClick={() => {
setResendIn(30);
setResent(true);
setError(undefined);
}}
className={link}
>
Resend code
</button>
)}
</div>
</div>
);
}
function NewPass({ onDone }: { onDone: (password: string) => void }) {
const reduce = useReducedMotion();
const [scope, animate] = useAnimate<HTMLFormElement>();
const [password, setPassword] = useState("");
const [show, setShow] = useState(false);
const [error, setError] = useState<string>();
const [busy, setBusy] = useState(false);
const pwRef = useRef<HTMLInputElement>(null);
async function submit(e: React.FormEvent) {
e.preventDefault();
if (password.length < 8) {
setError("Use at least 8 characters.");
if (!reduce && scope.current) animate(scope.current, { x: [0, -8, 7, -5, 3, 0] }, { duration: 0.42, ease: "easeOut" });
pwRef.current?.focus();
pwRef.current?.select();
return;
}
setBusy(true);
await wait(700);
setBusy(false);
onDone(password);
}
return (
<form ref={scope} onSubmit={submit} noValidate className="space-y-4">
<div>
<label htmlFor="af-new-password" className="mb-1.5 block text-[13px] font-medium">New password</label>
<div className="relative">
<input
ref={pwRef}
id="af-new-password"
name="new-password"
type={show ? "text" : "password"}
autoComplete="new-password"
autoFocus
value={password}
onChange={(e) => {
setPassword(e.target.value);
if (error) setError(undefined);
}}
aria-invalid={!!error}
aria-describedby={error ? "af-newpass-error" : undefined}
className={cn(field, "border-border pr-10")}
/>
<button
type="button"
onClick={() => setShow((v) => !v)}
aria-label={show ? "Hide password" : "Show password"}
aria-pressed={show}
className="absolute inset-y-0 right-1 my-auto grid size-8 place-items-center rounded-md text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
{show ? <EyeOff className="size-4" aria-hidden /> : <Eye className="size-4" aria-hidden />}
</button>
</div>
<FieldError id="af-newpass-error">{error}</FieldError>
</div>
<button type="submit" disabled={busy} className={primary}>
{busy ? <><Loader2 className="size-4 animate-spin" aria-hidden />Saving…</> : "Save password and sign in"}
</button>
</form>
);
}
function Forgot({ email, setEmail, onSent, onBack }: { email: string; setEmail: (v: string) => void; onSent: () => void; onBack: () => void }) {
const [error, setError] = useState<string>();
const [busy, setBusy] = useState(false);
return (
<form
noValidate
className="space-y-4"
onSubmit={async (e) => {
e.preventDefault();
if (!EMAIL.test(email)) return setError("Enter the email you signed up with.");
setBusy(true);
await wait(700);
setBusy(false);
onSent();
}}
>
<div>
<label htmlFor="af-reset-email" className="mb-1.5 block text-[13px] font-medium">Email</label>
<input
id="af-reset-email"
type="email"
autoComplete="email"
autoFocus
value={email}
onChange={(e) => {
setEmail(e.target.value);
setError(undefined);
}}
placeholder="you@company.com"
aria-invalid={!!error}
aria-describedby={error ? "af-reset-error" : undefined}
className={cn(field, "border-border")}
/>
<FieldError id="af-reset-error">{error}</FieldError>
</div>
<button type="submit" disabled={busy} className={primary}>
{busy ? <><Loader2 className="size-4 animate-spin" aria-hidden />Sending…</> : "Send reset link"}
</button>
<button type="button" onClick={onBack} className={cn(link, "mx-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground")}>
<ArrowLeft className="size-3.5" aria-hidden />Back to sign in
</button>
</form>
);
}
const copy: Record<Step, { title: string; body: (email: string) => string }> = {
signin: { title: "Welcome back", body: () => "Sign in to your workspace." },
otp: { title: "Check your authenticator", body: (e) => `Enter the 6-digit code we sent${e ? ` to ${e}` : ""}.` },
forgot: { title: "Reset your password", body: () => "We'll email you a link to choose a new one." },
sent: { title: "Check your inbox", body: (e) => `If ${e || "that address"} has an account, a reset link is on its way. It expires in 30 minutes.` },
newpass: { title: "Choose a new password", body: () => "At least 8 characters. Your old password stops working as soon as you save." },
done: { title: "You're in", body: () => "Redirecting to your dashboard…" },
};
export default function AuthFlowBlock() {
const reduce = useReducedMotion();
const [step, setStep] = useState<Step>("signin");
const [email, setEmail] = useState("");
const [dir, setDir] = useState(1);
const [lockout, setLockout] = useState<Lockout>({ attempts: 0, until: 0 });
const [otpIntent, setOtpIntent] = useState<"signin" | "reset">("signin");
const [acceptedPw, setAcceptedPw] = useState(DEMO_PASSWORD);
const go = (s: Step, d = 1) => {
setDir(d);
setStep(s);
};
return (
<section className="relative flex min-h-full w-full items-center justify-center overflow-hidden bg-muted/40 px-4 py-12">
<div aria-hidden className="pointer-events-none absolute inset-0 bg-[linear-gradient(to_right,var(--border)_1px,transparent_1px),linear-gradient(to_bottom,var(--border)_1px,transparent_1px)] bg-[size:48px_48px] [mask-image:radial-gradient(ellipse_at_center,black_20%,transparent_70%)]" />
<div className="relative w-full max-w-[400px]">
<motion.div
layout={!reduce}
transition={{ type: "spring", stiffness: 380, damping: 36 }}
className="overflow-hidden rounded-xl border border-border bg-card shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_0_0_1px_rgb(0_0_0/0.02),0_2px_4px_-2px_rgb(0_0_0/0.08),0_24px_48px_-24px_rgb(0_0_0/0.3)]"
>
<div className="px-6 pb-6 pt-7 sm:px-8 sm:pb-8">
<div className="mb-6 flex size-10 items-center justify-center rounded-lg bg-foreground text-background shadow-[inset_0_1px_0_rgb(255_255_255/0.2),0_4px_10px_-4px_rgb(0_0_0/0.4)]">
<AnimatePresence mode="wait" initial={false}>
<motion.span key={step === "otp" ? "shield" : step === "sent" || step === "forgot" ? "mail" : step === "newpass" ? "key" : step === "done" ? "check" : "logo"} initial={{ scale: 0.6, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.6, opacity: 0 }} transition={{ duration: 0.16 }}>
{step === "otp" ? <ShieldCheck className="size-5" aria-hidden /> : step === "sent" || step === "forgot" ? <Mail className="size-5" aria-hidden /> : step === "newpass" ? <KeyRound className="size-5" aria-hidden /> : step === "done" ? <Check className="size-5" aria-hidden /> : <span className="text-sm font-semibold">A</span>}
</motion.span>
</AnimatePresence>
</div>
<AnimatePresence mode="wait" initial={false} custom={dir}>
<motion.div
key={step}
custom={dir}
initial={reduce ? { opacity: 0 } : { opacity: 0, x: 24 * dir }}
animate={{ opacity: 1, x: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, x: -24 * dir }}
transition={{ duration: 0.22, ease: [0.22, 1, 0.36, 1] }}
>
<h2 className="text-xl font-semibold tracking-tight">{step === "otp" && otpIntent === "reset" ? "Check your inbox" : copy[step].title}</h2>
<p className="mt-1.5 text-pretty text-sm text-muted-foreground">{copy[step].body(email)}</p>
<div className="mt-6">
{step === "signin" ? <SignIn email={email} setEmail={setEmail} lockout={lockout} setLockout={setLockout} expected={acceptedPw} onDone={() => { setOtpIntent("signin"); go("otp"); }} onForgot={() => go("forgot")} /> : null}
{step === "otp" ? <Otp email={email} onDone={() => go(otpIntent === "reset" ? "newpass" : "done")} onBack={() => go(otpIntent === "reset" ? "sent" : "signin", -1)} /> : null}
{step === "forgot" ? <Forgot email={email} setEmail={setEmail} onSent={() => go("sent")} onBack={() => go("signin", -1)} /> : null}
{step === "sent" ? (
<div className="space-y-3">
<button type="button" onClick={() => { setOtpIntent("reset"); go("otp"); }} className={primary}>Enter a code instead</button>
<button type="button" onClick={() => go("signin", -1)} className={cn(link, "mx-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground")}>
<ArrowLeft className="size-3.5" aria-hidden />Back to sign in
</button>
</div>
) : null}
{step === "newpass" ? <NewPass onDone={(pw) => { setAcceptedPw(pw); go("done"); }} /> : null}
{step === "done" ? (
<div className="space-y-4">
<div className="h-1 overflow-hidden rounded-full bg-muted">
<motion.div className="h-full bg-foreground" initial={{ width: "0%" }} animate={{ width: "100%" }} transition={{ duration: reduce ? 0 : 1.6, ease: "easeInOut" }} />
</div>
<button type="button" onClick={() => go("signin", -1)} className={cn(link, "mx-auto block text-xs text-muted-foreground hover:text-foreground")}>Sign out and restart demo</button>
</div>
) : null}
</div>
</motion.div>
</AnimatePresence>
</div>
{step === "signin" ? (
<div className="border-t border-border bg-muted/40 px-6 py-3.5 text-center text-xs text-muted-foreground sm:px-8">
No account? <a href="#signup" className={link}>Create one</a>
</div>
) : null}
</motion.div>
<p className="mt-4 text-center font-mono text-[11px] text-muted-foreground">
Demo ·{" "}
{acceptedPw === DEMO_PASSWORD ? (
<>
password <span className="text-foreground">{DEMO_PASSWORD}</span> ·{" "}
</>
) : null}
code <span className="text-foreground">{DEMO_CODE}</span>
</p>
</div>
</section>
);
}