From c3808ca353c29d6adc05aa6f500bc6d68bdf6c0b Mon Sep 17 00:00:00 2001 From: "Rudy B." Date: Fri, 24 Apr 2026 16:50:30 +0200 Subject: [PATCH] feat(2FA): implement 2FA step in login flow --- src/app/api/auth/login/route.ts | 10 ++ src/app/login/LoginForm.tsx | 11 +- src/app/login/LoginPage.tsx | 13 +- .../login/two-factor/LoginTwoFactorPage.tsx | 142 ++++++++++++++++++ src/app/login/two-factor/page.tsx | 19 +++ src/components/common/OtpInput.tsx | 94 ++++++++++++ 6 files changed, 284 insertions(+), 5 deletions(-) create mode 100644 src/app/login/two-factor/LoginTwoFactorPage.tsx create mode 100644 src/app/login/two-factor/page.tsx create mode 100644 src/components/common/OtpInput.tsx diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts index 17ca2f7d9..c5d082e53 100644 --- a/src/app/api/auth/login/route.ts +++ b/src/app/api/auth/login/route.ts @@ -4,6 +4,7 @@ import { ROLES } from '@/lib/constants'; import { secret } from '@/lib/crypto'; import { createSecureToken } from '@/lib/jwt'; import { checkPassword } from '@/lib/password'; +import prisma from '@/lib/prisma'; import redis from '@/lib/redis'; import { parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; @@ -31,6 +32,15 @@ export async function POST(request: Request) { const { id, role, createdAt } = user; + // Check if 2FA is enabled for this user + const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId: id } }); + if (twoFactor?.isEnabled) { + const partialToken = createSecureToken({ userId: id, type: 'partial-auth' }, secret(), { + expiresIn: '5m', + }); + return json({ requiresTwoFactor: true, partialToken }); + } + let token: string; if (redis.enabled) { diff --git a/src/app/login/LoginForm.tsx b/src/app/login/LoginForm.tsx index 23101b947..90da15c56 100644 --- a/src/app/login/LoginForm.tsx +++ b/src/app/login/LoginForm.tsx @@ -22,9 +22,14 @@ export function LoginForm() { const handleSubmit = async (data: any) => { await mutateAsync(data, { - onSuccess: async ({ token, user }) => { - setClientAuthToken(token); - setUser(user); + onSuccess: async (response: any) => { + if (response.requiresTwoFactor) { + sessionStorage.setItem('umami.partial-token', response.partialToken); + router.push('/login/two-factor'); + return; + } + setClientAuthToken(response.token); + setUser(response.user); router.push('/'); }, }); diff --git a/src/app/login/LoginPage.tsx b/src/app/login/LoginPage.tsx index 7bb2e35fc..d0aa5ff69 100644 --- a/src/app/login/LoginPage.tsx +++ b/src/app/login/LoginPage.tsx @@ -1,8 +1,9 @@ 'use client'; import { Column } from '@umami/react-zen'; import { LoginForm } from './LoginForm'; +import { PropsWithChildren } from 'react'; -export function LoginPage() { +export function LoginPageWrapper({ children }: PropsWithChildren) { return ( - + {children} ); } + +export function LoginPage() { + return ( + + + + ); +} diff --git a/src/app/login/two-factor/LoginTwoFactorPage.tsx b/src/app/login/two-factor/LoginTwoFactorPage.tsx new file mode 100644 index 000000000..e9c8e6b28 --- /dev/null +++ b/src/app/login/two-factor/LoginTwoFactorPage.tsx @@ -0,0 +1,142 @@ +'use client'; +import { + Button, + Column, + Form, + FormButtons, + FormField, + FormSubmitButton, + Heading, + Icon, + Text, + TextField, +} from '@umami/react-zen'; +import { useRouter } from 'next/navigation'; +import { useEffect, useRef, useState } from 'react'; +import { OtpInput } from '@/components/common/OtpInput'; +import { useMessages, useTwoFactorVerifyMutation } from '@/components/hooks'; +import { Logo } from '@/components/svg'; +import { setClientAuthToken } from '@/lib/client'; +import { setUser } from '@/store/app'; + +export function LoginTwoFactorPage() { + const { t, labels, messages, getErrorMessage } = useMessages(); + const router = useRouter(); + const { mutateAsync, isPending } = useTwoFactorVerifyMutation(); + const partialTokenRef = useRef(null); + const [useBackup, setUseBackup] = useState(false); + const [otpValue, setOtpValue] = useState(''); + const [lockUntil, setLockUntil] = useState(null); + const [error, setError] = useState(null); + + // Redirect to the login page when no token + useEffect(() => { + const token = sessionStorage.getItem('umami.partial-token'); + if (!token) { + router.replace('/login'); + return; + } + sessionStorage.removeItem('umami.partial-token'); + partialTokenRef.current = token; + }, [router]); + + // Keep the locked state until the time is up + useEffect(() => { + if (!lockUntil) return; + const interval = setInterval(() => { + if (new Date() >= lockUntil) { + setLockUntil(null); + } + }, 1000); + return () => clearInterval(interval); + }, [lockUntil]); + + const submitVerification = async (token?: string, backupCode?: string) => { + const partialToken = partialTokenRef.current; + if (!partialToken) { + router.replace('/login'); + return; + } + + setError(null); + + try { + const data = await mutateAsync({ partialToken, token, backupCode }); + setClientAuthToken(data.token); + setUser(data.user); + router.push('/'); + } catch (err: any) { + if (err.lockedUntil) { + setLockUntil(new Date(err.lockedUntil)); + } + setError(getErrorMessage(err)); + } + }; + + const handleSubmit = async (data: any) => { + await submitVerification( + useBackup ? undefined : otpValue, + useBackup ? data.backupCode : undefined, + ); + }; + + const lockMessage = lockUntil + ? t(messages.twoFactorLockedMessage, { + time: lockUntil.toLocaleTimeString(), + }) + : null; + + return ( + + + + + umami + + {t(labels.twoFactorLogin)} + {t(messages.twoFactorLoginDescription)} + + {!!lockUntil && lockMessage && ( + {lockMessage} + )} + +
+ {!useBackup ? ( + + {t(labels.twoFactorEnterCode)} + { + setOtpValue(val); + if (error) setError(null); + }} + onComplete={val => submitVerification(val)} + disabled={!!lockUntil || isPending} + /> + + ) : ( + + + + )} + + + + {t(labels.twoFactorVerify)} + + +
+ + +
+
+ ); +} diff --git a/src/app/login/two-factor/page.tsx b/src/app/login/two-factor/page.tsx new file mode 100644 index 000000000..3f05bf7ec --- /dev/null +++ b/src/app/login/two-factor/page.tsx @@ -0,0 +1,19 @@ +import type { Metadata } from 'next'; +import { LoginTwoFactorPage } from './LoginTwoFactorPage'; +import { LoginPageWrapper } from '@/app/login/LoginPage'; + +export default async function () { + if (process.env.DISABLE_LOGIN || process.env.CLOUD_MODE) { + return null; + } + + return ( + + + + ); +} + +export const metadata: Metadata = { + title: 'Two-factor authentication', +}; diff --git a/src/components/common/OtpInput.tsx b/src/components/common/OtpInput.tsx new file mode 100644 index 000000000..dfce36dc5 --- /dev/null +++ b/src/components/common/OtpInput.tsx @@ -0,0 +1,94 @@ +'use client'; +import { useRef, ClipboardEvent, KeyboardEvent } from 'react'; +import {Row, TextField} from '@umami/react-zen'; + +interface OtpInputProps { + value: string; + onChange: (value: string) => void; + onComplete?: (value: string) => void; + disabled?: boolean; +} + +const LENGTH = 6; + +const focusInput = (el: HTMLDivElement | null) => el?.querySelector('input')?.focus(); + +export function OtpInput({ value, onChange, onComplete, disabled }: OtpInputProps) { + const digits = Array.from({ length: LENGTH }, (_, i) => value?.[i] ?? ''); + const refs = useRef<(HTMLDivElement | null)[]>([]); + + const update = (index: number, char: string) => { + const next = digits.slice(); + next[index] = char; + const newVal = next.join(''); + onChange(newVal); + if (newVal.length === LENGTH) { + onComplete?.(newVal); + } + }; + + const handleInput = (index: number, raw: string) => { + const char = raw.replace(/\D/g, '').slice(-1); + if (!char) return; + update(index, char); + if (index < LENGTH - 1) { + focusInput(refs.current[index + 1]); + } + }; + + const handleKeyDown = (index: number, e: KeyboardEvent) => { + if (e.key === 'Backspace') { + if (digits[index]) { + update(index, ''); + } else if (index > 0) { + update(index - 1, ''); + focusInput(refs.current[index - 1]); + } + } else if (e.key === 'ArrowLeft' && index > 0) { + focusInput(refs.current[index - 1]); + } else if (e.key === 'ArrowRight' && index < LENGTH - 1) { + focusInput(refs.current[index + 1]); + } + }; + + const handlePaste = (e: ClipboardEvent) => { + e.preventDefault(); + const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, LENGTH); + const next = Array.from({ length: LENGTH }, (_, i) => pasted[i] ?? ''); + const newVal = next.join(''); + onChange(newVal); + if (newVal.length === LENGTH) { + onComplete?.(newVal); + focusInput(refs.current[LENGTH - 1]); + } else { + focusInput(refs.current[pasted.length]); + } + }; + + return ( + + {digits.map((digit, i) => ( +
{ + refs.current[i] = el; + }} + > + handleInput(i, char)} + onKeyDown={e => handleKeyDown(i, e)} + onPaste={handlePaste} + isDisabled={disabled} + inputMode="numeric" + maxLength={1} + autoComplete="one-time-code" + aria-label={`Digit ${i + 1}`} + placeholder="0" + style={{width: 32}} + /> +
+ ))} +
+ ); +}