feat(2FA): implement 2FA step in login flow

This commit is contained in:
Rudy B. committed 2026-04-25 01:40:06 +02:00
1 parent 4a7e337954
commit c3808ca353
6 files changed
+284 -5

No files matched your search

+10
View File
@@ -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) {
+8 -3
View File
@@ -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('/');
},
});
+11 -2
View File
@@ -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 (
<Column
alignItems="center"
@@ -11,7 +12,15 @@ export function LoginPage() {
backgroundColor="surface-raised"
style={{ paddingTop: '15vh' }}
>
<LoginForm />
{children}
</Column>
);
}
export function LoginPage() {
return (
<LoginPageWrapper>
<LoginForm />
</LoginPageWrapper>
);
}
@@ -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<string | null>(null);
const [useBackup, setUseBackup] = useState(false);
const [otpValue, setOtpValue] = useState('');
const [lockUntil, setLockUntil] = useState<Date | null>(null);
const [error, setError] = useState<string | null>(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 (
<Column justifyContent="center" alignItems="center" gap="6">
<Icon size="lg">
<Logo />
</Icon>
<Heading>umami</Heading>
<Column gap="4" style={{ minWidth: 300 }}>
<Heading size="xl">{t(labels.twoFactorLogin)}</Heading>
<Text>{t(messages.twoFactorLoginDescription)}</Text>
{!!lockUntil && lockMessage && (
<Text style={{ color: 'var(--color-danger, red)' }}>{lockMessage}</Text>
)}
<Form onSubmit={handleSubmit} error={error ?? undefined} style={{ minWidth: 300 }}>
{!useBackup ? (
<Column gap="2">
<Text weight='bold' >{t(labels.twoFactorEnterCode)}</Text>
<OtpInput
value={otpValue}
onChange={val => {
setOtpValue(val);
if (error) setError(null);
}}
onComplete={val => submitVerification(val)}
disabled={!!lockUntil || isPending}
/>
</Column>
) : (
<FormField label={t(labels.twoFactorBackupCode)} name="backupCode">
<TextField autoComplete="off" />
</FormField>
)}
<FormButtons>
<FormSubmitButton
variant="primary"
style={{ flex: 1 }}
isDisabled={
!!lockUntil || isPending || (!useBackup && (otpValue.length !== 6 || !!error))
}
>
{t(labels.twoFactorVerify)}
</FormSubmitButton>
</FormButtons>
</Form>
<Button variant="quiet" onPress={() => setUseBackup(v => !v)}>
{useBackup ? t(labels.twoFactorLogin) : t(labels.twoFactorUseBackup)}
</Button>
</Column>
</Column>
);
}
+19
View File
@@ -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 (
<LoginPageWrapper>
<LoginTwoFactorPage />
</LoginPageWrapper>
);
}
export const metadata: Metadata = {
title: 'Two-factor authentication',
};
+94
View File
@@ -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<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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 (
<Row gap='2'>
{digits.map((digit, i) => (
<div
key={i}
ref={el => {
refs.current[i] = el;
}}
>
<TextField
value={digit}
onChange={char => 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}}
/>
</div>
))}
</Row>
);
}