Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.
TypeScript analyticsaudience-segmentationchartscohort-analysisgoogle-analyticsproduct-analyticsstatisticsuser-journeyweb-analytics
feat(2FA): implement 2FA step in login flow
Rudy B.c3808ca353c2
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 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.tsxindex 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.tsxindex 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 (<ColumnalignItems="center"@@ -11,7 +12,15 @@ export function LoginPage() {backgroundColor="surface-raised"style={{ paddingTop: '15vh' }}>- <LoginForm />+ {children}</Column>);}++export function LoginPage() {+ return (+ <LoginPageWrapper>+ <LoginForm />+ </LoginPageWrapper>+ );+}diff --git a/src/app/login/two-factor/LoginTwoFactorPage.tsx b/src/app/login/two-factor/LoginTwoFactorPage.tsxnew file mode 100644index 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<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>+ );+}diff --git a/src/app/login/two-factor/page.tsx b/src/app/login/two-factor/page.tsxnew file mode 100644index 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 (+ <LoginPageWrapper>+ <LoginTwoFactorPage />+ </LoginPageWrapper>+ );+}++export const metadata: Metadata = {+ title: 'Two-factor authentication',+};diff --git a/src/components/common/OtpInput.tsx b/src/components/common/OtpInput.tsxnew file mode 100644index 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<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>+ );+}