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',
};