Open-source personal finance manager. Self-hosted, privacy-first.
feat: add brute-force rate limiting and TOTP two-factor authentication (#52)
Tássio Noronhaa75893468fd5
diff --git a/backend/alembic/versions/021_user_totp_fields.py b/backend/alembic/versions/021_user_totp_fields.pynew file mode 100644index 00000000..fa13a089--- /dev/null+++ b/backend/alembic/versions/021_user_totp_fields.py@@ -0,0 +1,29 @@+"""add totp_secret and is_2fa_enabled to users++Revision ID: 021+Revises: 020+Create Date: 2026-04-02+"""++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "021"+down_revision: Union[str, None] = "020"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column("users", sa.Column("totp_secret", sa.String(32), nullable=True))+ op.add_column(+ "users",+ sa.Column("is_2fa_enabled", sa.Boolean(), nullable=False, server_default="0"),+ )+++def downgrade() -> None:+ op.drop_column("users", "is_2fa_enabled")+ op.drop_column("users", "totp_secret")diff --git a/backend/app/api/custom_auth.py b/backend/app/api/custom_auth.pynew file mode 100644index 00000000..da29e2c4--- /dev/null+++ b/backend/app/api/custom_auth.py@@ -0,0 +1,38 @@+import secrets++from fastapi import APIRouter, Depends, HTTPException+from fastapi.security import OAuth2PasswordRequestForm++from app.core.auth import get_jwt_strategy, get_user_manager+from app.core.redis import get_redis++router = APIRouter()++TEMP_TOKEN_TTL = 300 # 5 minutes++[email protected]("/login")+async def login(+ credentials: OAuth2PasswordRequestForm = Depends(),+ user_manager=Depends(get_user_manager),+):+ user = await user_manager.authenticate(credentials)+ if user is None or not user.is_active:+ raise HTTPException(status_code=400, detail="LOGIN_BAD_CREDENTIALS")++ if user.is_2fa_enabled and user.totp_secret:+ # Store temp token in Redis, return 2FA challenge+ r = await get_redis()+ temp_token = secrets.token_urlsafe(32)+ await r.set(f"2fa_temp:{temp_token}", str(user.id), ex=TEMP_TOKEN_TTL)+ return {"requires_2fa": True, "temp_token": temp_token}++ # Normal login — generate JWT+ strategy = get_jwt_strategy()+ token = await strategy.write_token(user)+ return {"access_token": token, "token_type": "bearer"}++[email protected]("/logout")+async def logout():+ return {"detail": "Logged out"}diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.pynew file mode 100644index 00000000..9a3652a9--- /dev/null+++ b/backend/app/api/two_factor.py@@ -0,0 +1,120 @@+import uuid++import pyotp+from fastapi import APIRouter, Depends, HTTPException+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user, get_jwt_strategy+from app.core.database import get_async_session+from app.core.redis import get_redis+from app.models.user import User+from app.schemas.two_factor import (+ TwoFactorDisableRequest,+ TwoFactorEnableRequest,+ TwoFactorSetupResponse,+ TwoFactorVerifyRequest,+)++router = APIRouter()++[email protected]("/2fa/setup", response_model=TwoFactorSetupResponse)+async def setup_2fa(+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+):+ secret = pyotp.random_base32()+ user.totp_secret = secret+ session.add(user)+ await session.commit()++ totp = pyotp.TOTP(secret)+ otpauth_uri = totp.provisioning_uri(name=user.email, issuer_name="Securo")++ return TwoFactorSetupResponse(secret=secret, otpauth_uri=otpauth_uri)++[email protected]("/2fa/enable")+async def enable_2fa(+ body: TwoFactorEnableRequest,+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+):+ if not user.totp_secret:+ raise HTTPException(status_code=400, detail="Call /2fa/setup first")++ totp = pyotp.TOTP(user.totp_secret)+ if not totp.verify(body.code):+ raise HTTPException(status_code=400, detail="Invalid 2FA code")++ user.is_2fa_enabled = True+ session.add(user)+ await session.commit()+ return {"detail": "2FA enabled"}++[email protected]("/2fa/disable")+async def disable_2fa(+ body: TwoFactorDisableRequest,+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+):+ from fastapi_users.db import SQLAlchemyUserDatabase+ from fastapi.security import OAuth2PasswordRequestForm++ # Verify password by authenticating+ user_db = SQLAlchemyUserDatabase(session, User)+ from app.core.auth import UserManager+ user_manager = UserManager(user_db)++ creds = OAuth2PasswordRequestForm(username=user.email, password=body.password)+ authenticated = await user_manager.authenticate(creds)+ if authenticated is None:+ raise HTTPException(status_code=400, detail="Invalid password")++ # Verify TOTP code+ if not user.totp_secret:+ raise HTTPException(status_code=400, detail="2FA is not set up")++ totp = pyotp.TOTP(user.totp_secret)+ if not totp.verify(body.code):+ raise HTTPException(status_code=400, detail="Invalid 2FA code")++ user.totp_secret = None+ user.is_2fa_enabled = False+ session.add(user)+ await session.commit()+ return {"detail": "2FA disabled"}++[email protected]("/2fa/verify")+async def verify_2fa(+ body: TwoFactorVerifyRequest,+ session: AsyncSession = Depends(get_async_session),+):+ r = await get_redis()+ redis_key = f"2fa_temp:{body.temp_token}"+ user_id_str = await r.get(redis_key)++ if not user_id_str:+ raise HTTPException(status_code=401, detail="Invalid or expired token")++ # Load user+ result = await session.execute(select(User).where(User.id == uuid.UUID(user_id_str)))+ user = result.scalar_one_or_none()+ if not user or not user.totp_secret:+ raise HTTPException(status_code=401, detail="Invalid token")++ # Verify TOTP+ totp = pyotp.TOTP(user.totp_secret)+ if not totp.verify(body.code):+ raise HTTPException(status_code=400, detail="Invalid 2FA code")++ # Delete temp token+ await r.delete(redis_key)++ # Generate JWT+ strategy = get_jwt_strategy()+ token = await strategy.write_token(user)+ return {"access_token": token, "token_type": "bearer"}diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex 7bcd71c9..322e761f 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -13,7 +13,7 @@ class Settings(BaseSettings):# Authsecret_key: str = "change-me-in-production"algorithm: str = "HS256"- access_token_expire_minutes: int = 60 * 24 * 7 # 7 days+ access_token_expire_minutes: int = 60 * 24 # 24 hours# Pluggypluggy_client_id: str = ""diff --git a/backend/app/core/rate_limit.py b/backend/app/core/rate_limit.pynew file mode 100644index 00000000..9ee4729c--- /dev/null+++ b/backend/app/core/rate_limit.py@@ -0,0 +1,41 @@+import time++from fastapi import HTTPException, Request++from app.core.redis import get_redis+++class RateLimiter:+ def __init__(self, max_requests: int, window_seconds: int):+ self.max_requests = max_requests+ self.window_seconds = window_seconds++ async def __call__(self, request: Request) -> None:+ client_ip = request.client.host if request.client else "unknown"+ key = f"rate_limit:{request.url.path}:{client_ip}"++ r = await get_redis()+ now = time.time()+ window_start = now - self.window_seconds++ pipe = r.pipeline()+ pipe.zremrangebyscore(key, 0, window_start)+ pipe.zcard(key)+ pipe.zadd(key, {str(now): now})+ pipe.expire(key, self.window_seconds)+ results = await pipe.execute()++ request_count = results[1]++ if request_count >= self.max_requests:+ retry_after = self.window_seconds+ raise HTTPException(+ status_code=429,+ detail="Too many requests",+ headers={"Retry-After": str(retry_after)},+ )+++login_rate_limit = RateLimiter(max_requests=5, window_seconds=60)+register_rate_limit = RateLimiter(max_requests=3, window_seconds=3600)+password_reset_rate_limit = RateLimiter(max_requests=3, window_seconds=3600)diff --git a/backend/app/core/redis.py b/backend/app/core/redis.pynew file mode 100644index 00000000..3239f923--- /dev/null+++ b/backend/app/core/redis.py@@ -0,0 +1,22 @@+from typing import Optional++import redis.asyncio as redis++from app.core.config import get_settings++_redis: Optional[redis.Redis] = None+++async def get_redis() -> redis.Redis:+ global _redis+ if _redis is None:+ settings = get_settings()+ _redis = redis.from_url(settings.redis_url, decode_responses=True)+ return _redis+++async def close_redis() -> None:+ global _redis+ if _redis is not None:+ await _redis.aclose()+ _redis = Nonediff --git a/backend/app/main.py b/backend/app/main.pyindex 6c0894b9..2d77a89d 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -9,6 +9,7 @@ from app.api.budgets import router as budgets_routerfrom app.api.categories import router as categories_routerfrom app.api.category_groups import router as category_groups_routerfrom app.api.connections import router as connections_router+from app.api.custom_auth import router as custom_auth_routerfrom app.api.dashboard import router as dashboard_routerfrom app.api.import_logs import router as import_logs_routerfrom app.api.import_transactions import router as import_router@@ -24,9 +25,12 @@ from app.api.attachments import router as attachments_routerfrom app.api.payees import router as payees_routerfrom app.api.settings import router as settings_routerfrom app.api.transactions import router as transactions_router+from app.api.two_factor import router as two_factor_routerfrom app.api.admin import router as admin_router, check_registration_enabled-from app.core.auth import auth_backend, fastapi_users+from app.core.auth import fastapi_usersfrom app.core.config import get_settings+from app.core.rate_limit import login_rate_limit, register_rate_limit, password_reset_rate_limit+from app.core.redis import close_redisfrom app.schemas.user import UserCreate, UserRead, UserUpdatelogger = logging.getLogger(__name__)@@ -44,6 +48,8 @@ async def lifespan(app: FastAPI):except Exception:logger.exception("Startup: failed to dispatch sync task")yield+ # Shutdown+ await close_redis()app = FastAPI(@@ -61,9 +67,15 @@ app.add_middleware(allow_headers=["*"],)-# Auth routes+# Auth routes — custom login/logout with 2FA support (mounted first to take precedence)app.include_router(- fastapi_users.get_auth_router(auth_backend),+ custom_auth_router,+ prefix="/api/auth",+ tags=["auth"],+ dependencies=[Depends(login_rate_limit)],+)+app.include_router(+ two_factor_router,prefix="/api/auth",tags=["auth"],)@@ -71,12 +83,13 @@ app.include_router(fastapi_users.get_register_router(UserRead, UserCreate),prefix="/api/auth",tags=["auth"],- dependencies=[Depends(check_registration_enabled)],+ dependencies=[Depends(check_registration_enabled), Depends(register_rate_limit)],)app.include_router(fastapi_users.get_reset_password_router(),prefix="/api/auth",tags=["auth"],+ dependencies=[Depends(password_reset_rate_limit)],)app.include_router(fastapi_users.get_users_router(UserRead, UserUpdate),diff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex cb31f9a2..50555685 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -1,7 +1,7 @@from typing import TYPE_CHECKING, Optionalfrom fastapi_users.db import SQLAlchemyBaseUserTableUUID-from sqlalchemy import JSON+from sqlalchemy import JSON, Boolean, Stringfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom app.core.database import Base@@ -25,6 +25,9 @@ class User(SQLAlchemyBaseUserTableUUID, Base):},)+ totp_secret: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default=None)+ is_2fa_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0")+categories: Mapped[list["Category"]] = relationship(back_populates="user", cascade="all, delete-orphan")category_groups: Mapped[list["CategoryGroup"]] = relationship(back_populates="user", cascade="all, delete-orphan")bank_connections: Mapped[list["BankConnection"]] = relationship(back_populates="user", cascade="all, delete-orphan")diff --git a/backend/app/schemas/two_factor.py b/backend/app/schemas/two_factor.pynew file mode 100644index 00000000..8b8eb7dc--- /dev/null+++ b/backend/app/schemas/two_factor.py@@ -0,0 +1,20 @@+from pydantic import BaseModel, Field+++class TwoFactorSetupResponse(BaseModel):+ secret: str+ otpauth_uri: str+++class TwoFactorEnableRequest(BaseModel):+ code: str = Field(..., min_length=6, max_length=6, pattern=r"^\d{6}$")+++class TwoFactorDisableRequest(BaseModel):+ password: str+ code: str = Field(..., min_length=6, max_length=6, pattern=r"^\d{6}$")+++class TwoFactorVerifyRequest(BaseModel):+ temp_token: str+ code: str = Field(..., min_length=6, max_length=6, pattern=r"^\d{6}$")diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.pyindex b58071d0..619d78a3 100644--- a/backend/app/schemas/user.py+++ b/backend/app/schemas/user.py@@ -15,6 +15,7 @@ class UserPreferences(BaseModel):class UserRead(schemas.BaseUser[uuid.UUID]):preferences: Optional[dict] = None+ is_2fa_enabled: bool = Falseclass UserCreate(schemas.BaseUserCreate):diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex 6b075fe4..45761f26 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -19,6 +19,8 @@ dependencies = ["ofxparse>=0.21","celery[redis]>=5.3.0","aiofiles>=24.0",+ "redis[hiredis]>=5.0.0",+ "pyotp>=2.9.0",][project.optional-dependencies]diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex d06b3bf9..70d4d5bd 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -329,6 +329,70 @@ async def test_rules(return rules+@pytest_asyncio.fixture+async def test_user_with_2fa(session: AsyncSession, clean_db) -> User:+ """Create a test user with 2FA enabled."""+ import bcrypt as _bcrypt+ import pyotp++ hashed = _bcrypt.hashpw(b"testpass123", _bcrypt.gensalt()).decode()+ totp_secret = pyotp.random_base32()+ user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=hashed,+ is_active=True,+ is_superuser=False,+ is_verified=True,+ totp_secret=totp_secret,+ is_2fa_enabled=True,+ preferences={+ "language": "en",+ "date_format": "MM/DD/YYYY",+ "timezone": "UTC",+ "currency_display": "USD",+ },+ )+ session.add(user)+ await session.commit()+ await session.refresh(user)+ return user++[email protected](autouse=True)+def _mock_redis():+ """Provide a no-op Redis mock so rate limiting never blocks tests."""+ mock = AsyncMock()+ # Pipeline mock that always reports 0 prior requests (never rate-limits)+ pipe_mock = AsyncMock()+ pipe_mock.zremrangebyscore = AsyncMock()+ pipe_mock.zcard = AsyncMock()+ pipe_mock.zadd = AsyncMock()+ pipe_mock.expire = AsyncMock()+ pipe_mock.execute = AsyncMock(return_value=[0, 0, True, True])+ mock.pipeline = lambda: pipe_mock+ # Key-value ops for 2FA temp tokens+ mock.get = AsyncMock(return_value=None)+ mock.set = AsyncMock()+ mock.delete = AsyncMock()++ async def _fake_get_redis():+ return mock++ # Reset the cached singleton so no real Redis connection leaks into tests+ import app.core.redis as redis_mod+ original = redis_mod._redis+ redis_mod._redis = None++ with patch("app.core.redis.get_redis", _fake_get_redis), \+ patch("app.core.rate_limit.get_redis", _fake_get_redis), \+ patch("app.api.custom_auth.get_redis", _fake_get_redis), \+ patch("app.api.two_factor.get_redis", _fake_get_redis):+ yield mock++ redis_mod._redis = original++@pytest.fixture(autouse=True)def _no_external_fx_sync():"""Prevent tests from hitting the real OpenExchangeRates API."""diff --git a/backend/tests/test_rate_limit.py b/backend/tests/test_rate_limit.pynew file mode 100644index 00000000..1063fd8e--- /dev/null+++ b/backend/tests/test_rate_limit.py@@ -0,0 +1,68 @@+from unittest.mock import AsyncMock, patch++import pytest+from httpx import AsyncClient++[email protected](autouse=True)+def _override_redis_with_counter(_mock_redis):+ """Override the autouse _mock_redis with one that counts requests for rate limiting."""+ counters = {}++ def make_pipeline():+ pipe = AsyncMock()+ _path = [None]++ # Pipeline methods are called synchronously (NOT awaited), so use plain functions+ def capture_key(key, *args):+ _path[0] = key++ pipe.zremrangebyscore = capture_key+ pipe.zcard = lambda *a: None+ pipe.zadd = lambda *a, **kw: None+ pipe.expire = lambda *a: None++ async def execute():+ key = _path[0]+ count = counters.get(key, 0) # count BEFORE this request (zcard result)+ counters[key] = count + 1 # zadd increments+ return [0, count, True, True]++ pipe.execute = AsyncMock(side_effect=execute)+ return pipe++ mock = AsyncMock()+ mock.pipeline = make_pipeline+ mock.get = AsyncMock(return_value=None)+ mock.set = AsyncMock()+ mock.delete = AsyncMock()++ async def _fake():+ return mock++ with patch("app.core.redis.get_redis", _fake), \+ patch("app.core.rate_limit.get_redis", _fake), \+ patch("app.api.custom_auth.get_redis", _fake), \+ patch("app.api.two_factor.get_redis", _fake):+ yield counters+++async def test_login_rate_limit(client: AsyncClient, test_user):+ """After 5 failed attempts, the 6th should get 429."""+ for i in range(5):+ response = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "wrongpassword"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ # Should get 400 (bad credentials), not 429+ assert response.status_code == 400, f"Request {i+1} got {response.status_code}"++ # 6th request should be rate limited+ response = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "wrongpassword"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert response.status_code == 429+ assert "Retry-After" in response.headersdiff --git a/backend/tests/test_two_factor.py b/backend/tests/test_two_factor.pynew file mode 100644index 00000000..025c075d--- /dev/null+++ b/backend/tests/test_two_factor.py@@ -0,0 +1,177 @@+from unittest.mock import AsyncMock, patch++import pyotp+import pytest+from httpx import AsyncClient+++def _make_redis_mock_with_store():+ """Create a Redis mock that actually stores and retrieves key-value pairs."""+ store = {}+ mock = AsyncMock()++ async def mock_get(key):+ return store.get(key)++ async def mock_set(key, value, ex=None):+ store[key] = value++ async def mock_delete(key):+ store.pop(key, None)++ mock.get = AsyncMock(side_effect=mock_get)+ mock.set = AsyncMock(side_effect=mock_set)+ mock.delete = AsyncMock(side_effect=mock_delete)++ # Pipeline for rate limiter (always allow)+ pipe_mock = AsyncMock()+ pipe_mock.zremrangebyscore = AsyncMock()+ pipe_mock.zcard = AsyncMock()+ pipe_mock.zadd = AsyncMock()+ pipe_mock.expire = AsyncMock()+ pipe_mock.execute = AsyncMock(return_value=[0, 0, True, True])+ mock.pipeline = lambda: pipe_mock++ return mock++[email protected](autouse=True)+def _override_redis_with_store(_mock_redis):+ """Override the autouse _mock_redis with one that has a real key-value store."""+ mock = _make_redis_mock_with_store()++ async def _fake():+ return mock++ with patch("app.core.redis.get_redis", _fake), \+ patch("app.core.rate_limit.get_redis", _fake), \+ patch("app.api.custom_auth.get_redis", _fake), \+ patch("app.api.two_factor.get_redis", _fake):+ yield mock+++async def test_setup_2fa(client: AsyncClient, auth_headers: dict):+ response = await client.post("/api/auth/2fa/setup", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert "secret" in data+ assert "otpauth_uri" in data+ assert "otpauth://totp/" in data["otpauth_uri"]+++async def test_enable_2fa(client: AsyncClient, auth_headers: dict, test_user):+ # First setup+ setup_resp = await client.post("/api/auth/2fa/setup", headers=auth_headers)+ secret = setup_resp.json()["secret"]++ # Generate valid code+ totp = pyotp.TOTP(secret)+ code = totp.now()++ response = await client.post(+ "/api/auth/2fa/enable",+ json={"code": code},+ headers=auth_headers,+ )+ assert response.status_code == 200+ assert response.json()["detail"] == "2FA enabled"+++async def test_enable_2fa_invalid_code(client: AsyncClient, auth_headers: dict, test_user):+ # First setup+ await client.post("/api/auth/2fa/setup", headers=auth_headers)++ response = await client.post(+ "/api/auth/2fa/enable",+ json={"code": "000000"},+ headers=auth_headers,+ )+ assert response.status_code == 400+++async def test_login_with_2fa(client: AsyncClient, test_user_with_2fa):+ response = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert response.status_code == 200+ data = response.json()+ assert data["requires_2fa"] is True+ assert "temp_token" in data+++async def test_verify_2fa(client: AsyncClient, test_user_with_2fa):+ # Login to get temp token+ login_resp = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ temp_token = login_resp.json()["temp_token"]++ # Generate valid TOTP code+ totp = pyotp.TOTP(test_user_with_2fa.totp_secret)+ code = totp.now()++ response = await client.post(+ "/api/auth/2fa/verify",+ json={"temp_token": temp_token, "code": code},+ )+ assert response.status_code == 200+ data = response.json()+ assert "access_token" in data+ assert data["token_type"] == "bearer"+++async def test_verify_2fa_invalid_code(client: AsyncClient, test_user_with_2fa):+ # Login to get temp token+ login_resp = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ temp_token = login_resp.json()["temp_token"]++ response = await client.post(+ "/api/auth/2fa/verify",+ json={"temp_token": temp_token, "code": "000000"},+ )+ assert response.status_code == 400+++async def test_verify_2fa_expired_token(client: AsyncClient):+ response = await client.post(+ "/api/auth/2fa/verify",+ json={"temp_token": "nonexistent-token", "code": "123456"},+ )+ assert response.status_code == 401+++async def test_disable_2fa(client: AsyncClient, test_user_with_2fa):+ # Get auth token for 2FA user by verifying 2FA+ login_resp = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ temp_token = login_resp.json()["temp_token"]+ totp = pyotp.TOTP(test_user_with_2fa.totp_secret)+ code = totp.now()++ verify_resp = await client.post(+ "/api/auth/2fa/verify",+ json={"temp_token": temp_token, "code": code},+ )+ token = verify_resp.json()["access_token"]+ headers = {"Authorization": f"Bearer {token}"}++ # Now disable 2FA+ new_code = totp.now()+ response = await client.post(+ "/api/auth/2fa/disable",+ json={"password": "testpass123", "code": new_code},+ headers=headers,+ )+ assert response.status_code == 200+ assert response.json()["detail"] == "2FA disabled"diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex c1014973..c9d00dc8 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -19,6 +19,7 @@"lucide-react": "^0.575.0","next-themes": "^0.4.6","pdfjs-dist": "^5.5.207",+ "qrcode.react": "^4.2.0","radix-ui": "^1.4.3","react": "^19.2.0","react-dom": "^19.2.0",@@ -8781,6 +8782,15 @@"node": ">=6"}},+ "node_modules/qrcode.react": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",+ "integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/qs": {"version": "6.15.0","resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 28d7f49a..2b1ad796 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -22,6 +22,7 @@"lucide-react": "^0.575.0","next-themes": "^0.4.6","pdfjs-dist": "^5.5.207",+ "qrcode.react": "^4.2.0","radix-ui": "^1.4.3","react": "^19.2.0","react-dom": "^19.2.0",diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex c7f644d9..a0287cd5 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -41,9 +41,11 @@ import {KeyRound,HardDriveDownload,Shield,+ ShieldCheck,} from 'lucide-react'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { ChangePasswordDialog } from '@/components/change-password-dialog'+import { TwoFactorSetup } from '@/components/two-factor-setup'type NavItem =| { type: 'link'; key: string; path: string; icon: React.ElementType }@@ -82,6 +84,7 @@ export function AppLayout() {const [accountsExpanded, setAccountsExpanded] = useState(true)const { privacyMode, togglePrivacyMode, mask } = usePrivacyMode()const [changePasswordOpen, setChangePasswordOpen] = useState(false)+ const [twoFactorOpen, setTwoFactorOpen] = useState(false)const [backingUp, setBackingUp] = useState(false)const showTour = user && !user.preferences?.onboarding_completed && !localStorage.getItem('onboarding_completed')@@ -133,7 +136,7 @@ export function AppLayout() {>{privacyMode ? <EyeOff size={18} /> : <Eye size={18} />}</button>- <UserMenu userInitial={userInitial} logout={logout} onChangePassword={() => setChangePasswordOpen(true)} backingUp={backingUp} onBackup={async () => {+ <UserMenu userInitial={userInitial} logout={logout} onChangePassword={() => setChangePasswordOpen(true)} onTwoFactor={() => setTwoFactorOpen(true)} backingUp={backingUp} onBackup={async () => {setBackingUp(true)try {await backupApi.download()@@ -368,6 +371,13 @@ export function AppLayout() {<KeyRound size={14} />{t('auth.changePassword')}</DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => setTwoFactorOpen(true)}+ className="flex items-center gap-2"+ >+ <ShieldCheck size={14} />+ {t('auth.twoFactorTitle')}+ </DropdownMenuItem><DropdownMenuItemdisabled={backingUp}onClick={async () => {@@ -409,11 +419,12 @@ export function AppLayout() {{showTour && <OnboardingTour onComplete={handleTourComplete} />}<ChangePasswordDialog open={changePasswordOpen} onClose={() => setChangePasswordOpen(false)} />+ <TwoFactorSetup open={twoFactorOpen} onClose={() => setTwoFactorOpen(false)} /></div>)}-function UserMenu({ userInitial, logout, onChangePassword, onBackup, backingUp, dark, isAdmin }: { userInitial: string; logout: () => void; onChangePassword: () => void; onBackup: () => void; backingUp: boolean; dark?: boolean; isAdmin?: boolean }) {+function UserMenu({ userInitial, logout, onChangePassword, onTwoFactor, onBackup, backingUp, dark, isAdmin }: { userInitial: string; logout: () => void; onChangePassword: () => void; onTwoFactor: () => void; onBackup: () => void; backingUp: boolean; dark?: boolean; isAdmin?: boolean }) {const { t } = useTranslation()const nav = useNavigate()return (@@ -441,6 +452,10 @@ function UserMenu({ userInitial, logout, onChangePassword, onBackup, backingUp,<KeyRound size={14} />{t('auth.changePassword')}</DropdownMenuItem>+ <DropdownMenuItem onClick={onTwoFactor} className="flex items-center gap-2">+ <ShieldCheck size={14} />+ {t('auth.twoFactorTitle')}+ </DropdownMenuItem><DropdownMenuItem disabled={backingUp} onClick={onBackup} className="flex items-center gap-2"><HardDriveDownload size={14} />{backingUp ? t('backup.downloading') : t('backup.button')}diff --git a/frontend/src/components/two-factor-setup.tsx b/frontend/src/components/two-factor-setup.tsxnew file mode 100644index 00000000..4f38f5f3--- /dev/null+++ b/frontend/src/components/two-factor-setup.tsx@@ -0,0 +1,209 @@+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { QRCodeSVG } from 'qrcode.react'+import { useAuth } from '@/contexts/auth-context'+import { auth } from '@/lib/api'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'++interface TwoFactorSetupProps {+ open: boolean+ onClose: () => void+}++export function TwoFactorSetup({ open, onClose }: TwoFactorSetupProps) {+ const { t } = useTranslation()+ const { user, updateUser } = useAuth()+ const is2faEnabled = user?.is_2fa_enabled ?? false++ // Enable flow+ const [secret, setSecret] = useState('')+ const [otpauthUri, setOtpauthUri] = useState('')+ const [setupCode, setSetupCode] = useState('')+ const [setupLoading, setSetupLoading] = useState(false)+ const [setupStep, setSetupStep] = useState<'idle' | 'qr'>('idle')+ const [error, setError] = useState('')++ // Disable flow+ const [disablePassword, setDisablePassword] = useState('')+ const [disableCode, setDisableCode] = useState('')+ const [disableLoading, setDisableLoading] = useState(false)++ const handleSetup = async () => {+ setSetupLoading(true)+ setError('')+ try {+ const data = await auth.setup2fa()+ setSecret(data.secret)+ setOtpauthUri(data.otpauth_uri)+ setSetupStep('qr')+ } catch {+ setError(t('common.error'))+ } finally {+ setSetupLoading(false)+ }+ }++ const handleEnable = async (e: React.FormEvent) => {+ e.preventDefault()+ setSetupLoading(true)+ setError('')+ try {+ await auth.enable2fa(setupCode)+ toast.success(t('auth.twoFactorEnabled'))+ if (user) updateUser({ ...user, is_2fa_enabled: true })+ handleClose()+ } catch {+ setError(t('auth.invalid2faCode'))+ } finally {+ setSetupLoading(false)+ }+ }++ const handleDisable = async (e: React.FormEvent) => {+ e.preventDefault()+ setDisableLoading(true)+ setError('')+ try {+ await auth.disable2fa(disablePassword, disableCode)+ toast.success(t('auth.twoFactorDisabled'))+ if (user) updateUser({ ...user, is_2fa_enabled: false })+ handleClose()+ } catch {+ setError(t('auth.invalid2faCode'))+ } finally {+ setDisableLoading(false)+ }+ }++ const handleClose = () => {+ setSecret('')+ setOtpauthUri('')+ setSetupCode('')+ setSetupStep('idle')+ setError('')+ setDisablePassword('')+ setDisableCode('')+ onClose()+ }++ if (is2faEnabled) {+ // Disable flow+ return (+ <Dialog open={open} onOpenChange={(v) => !v && handleClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('auth.disable2fa')}</DialogTitle>+ </DialogHeader>+ <form onSubmit={handleDisable} className="space-y-4">+ <p className="text-sm text-muted-foreground">{t('auth.disable2faDescription')}</p>+ <div className="space-y-2">+ <Label htmlFor="disable-password">{t('auth.password')}</Label>+ <Input+ id="disable-password"+ type="password"+ value={disablePassword}+ onChange={(e) => setDisablePassword(e.target.value)}+ required+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="disable-code">{t('auth.twoFactor')}</Label>+ <Input+ id="disable-code"+ type="text"+ inputMode="numeric"+ value={disableCode}+ onChange={(e) => setDisableCode(e.target.value.replace(/\D/g, '').slice(0, 6))}+ placeholder="000000"+ className="text-center text-lg tracking-[0.3em] font-mono"+ maxLength={6}+ required+ />+ </div>+ {error && <p className="text-sm text-destructive">{error}</p>}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={handleClose}>+ {t('common.cancel')}+ </Button>+ <Button type="submit" variant="destructive" disabled={disableLoading || disableCode.length !== 6}>+ {disableLoading ? t('common.loading') : t('auth.disable2fa')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+ }++ // Enable flow+ return (+ <Dialog open={open} onOpenChange={(v) => !v && handleClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('auth.setup2fa')}</DialogTitle>+ </DialogHeader>++ {setupStep === 'idle' ? (+ <div className="space-y-4">+ <p className="text-sm text-muted-foreground">{t('auth.setup2faDescription')}</p>+ {error && <p className="text-sm text-destructive">{error}</p>}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={handleClose}>+ {t('common.cancel')}+ </Button>+ <Button onClick={handleSetup} disabled={setupLoading}>+ {setupLoading ? t('common.loading') : t('auth.enable2fa')}+ </Button>+ </DialogFooter>+ </div>+ ) : (+ <form onSubmit={handleEnable} className="space-y-4">+ <div className="flex flex-col items-center gap-4">+ <div className="bg-white p-3 rounded-lg">+ <QRCodeSVG value={otpauthUri} size={180} />+ </div>+ <div className="text-center">+ <p className="text-xs text-muted-foreground mb-1">{t('auth.manualEntry')}</p>+ <code className="text-xs bg-muted px-2 py-1 rounded select-all">{secret}</code>+ </div>+ </div>+ <div className="space-y-2">+ <Label htmlFor="setup-code">{t('auth.twoFactor')}</Label>+ <Input+ id="setup-code"+ type="text"+ inputMode="numeric"+ value={setupCode}+ onChange={(e) => setSetupCode(e.target.value.replace(/\D/g, '').slice(0, 6))}+ placeholder="000000"+ className="text-center text-lg tracking-[0.3em] font-mono"+ maxLength={6}+ required+ autoFocus+ />+ </div>+ {error && <p className="text-sm text-destructive">{error}</p>}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={handleClose}>+ {t('common.cancel')}+ </Button>+ <Button type="submit" disabled={setupLoading || setupCode.length !== 6}>+ {setupLoading ? t('common.loading') : t('auth.verify')}+ </Button>+ </DialogFooter>+ </form>+ )}+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-context.tsxindex 712a3115..b0fde987 100644--- a/frontend/src/contexts/auth-context.tsx+++ b/frontend/src/contexts/auth-context.tsx@@ -3,11 +3,17 @@ import { useQueryClient } from '@tanstack/react-query'import { auth } from '@/lib/api'import type { User } from '@/types'+interface LoginResult {+ requires_2fa: boolean+ temp_token?: string+}+interface AuthContextType {user: User | nulltoken: string | nullisLoading: boolean- login: (email: string, password: string) => Promise<void>+ login: (email: string, password: string) => Promise<LoginResult>+ verify2fa: (tempToken: string, code: string) => Promise<void>loginWithToken: (accessToken: string) => voidregister: (email: string, password: string, preferences?: Record<string, string>) => Promise<void>updateUser: (user: User) => void@@ -48,13 +54,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {return () => window.removeEventListener('storage', handleStorage)}, [])- const login = useCallback(async (email: string, password: string) => {+ const login = useCallback(async (email: string, password: string): Promise<LoginResult> => {const data = await auth.login(email, password)++ if (data.requires_2fa) {+ return { requires_2fa: true, temp_token: data.temp_token }+ }+const accessToken = data.access_tokenlocalStorage.setItem('token', accessToken)setToken(accessToken)const me = await auth.me()setUser(me)+ return { requires_2fa: false }+ }, [])++ const verify2fa = useCallback(async (tempToken: string, code: string) => {+ const data = await auth.verify2fa(tempToken, code)+ localStorage.setItem('token', data.access_token)+ setToken(data.access_token)+ const me = await auth.me()+ setUser(me)}, [])const loginWithToken = useCallback((accessToken: string) => {@@ -80,7 +100,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {}, [queryClient])return (- <AuthContext.Provider value={{ user, token, isLoading, login, loginWithToken, register, updateUser, logout }}>+ <AuthContext.Provider value={{ user, token, isLoading, login, verify2fa, loginWithToken, register, updateUser, logout }}>{children}</AuthContext.Provider>)diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 410346be..81043471 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -94,6 +94,20 @@ export const auth = {const { data } = await api.patch('/users/me', { password })return data},+ setup2fa: async (): Promise<{ secret: string; otpauth_uri: string }> => {+ const { data } = await api.post('/auth/2fa/setup')+ return data+ },+ enable2fa: async (code: string): Promise<void> => {+ await api.post('/auth/2fa/enable', { code })+ },+ disable2fa: async (password: string, code: string): Promise<void> => {+ await api.post('/auth/2fa/disable', { password, code })+ },+ verify2fa: async (tempToken: string, code: string): Promise<{ access_token: string; token_type: string }> => {+ const { data } = await api.post('/auth/2fa/verify', { temp_token: tempToken, code })+ return data+ },}// Categoriesdiff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex b656fba5..08f75089 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -42,7 +42,21 @@"passwordMismatch": "Passwords do not match","registrationError": "Error creating account. Please try again.","registerDescription": "Create your account to get started",- "currency": "Currency"+ "currency": "Currency",+ "twoFactor": "Two-factor code",+ "twoFactorTitle": "Two-Factor Auth",+ "twoFactorDescription": "Enter the 6-digit code from your authenticator app",+ "verify": "Verify",+ "invalid2faCode": "Invalid verification code",+ "tooManyAttempts": "Too many attempts. Please try again later.",+ "setup2fa": "Set Up Two-Factor Authentication",+ "setup2faDescription": "Add an extra layer of security to your account by enabling two-factor authentication with an authenticator app.",+ "manualEntry": "Or enter this key manually:",+ "enable2fa": "Enable 2FA",+ "disable2fa": "Disable 2FA",+ "disable2faDescription": "Enter your password and a verification code to disable two-factor authentication.",+ "twoFactorEnabled": "Two-factor authentication enabled",+ "twoFactorDisabled": "Two-factor authentication disabled"},"dashboard": {"title": "Dashboard",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 9e6ede8c..3038ad96 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -42,7 +42,21 @@"passwordMismatch": "As senhas não conferem","registrationError": "Erro ao criar conta. Tente novamente.","registerDescription": "Crie sua conta para começar",- "currency": "Moeda"+ "currency": "Moeda",+ "twoFactor": "Código de verificação",+ "twoFactorTitle": "Autenticação 2FA",+ "twoFactorDescription": "Digite o código de 6 dígitos do seu app autenticador",+ "verify": "Verificar",+ "invalid2faCode": "Código de verificação inválido",+ "tooManyAttempts": "Muitas tentativas. Tente novamente mais tarde.",+ "setup2fa": "Configurar Autenticação em Dois Fatores",+ "setup2faDescription": "Adicione uma camada extra de segurança à sua conta ativando a autenticação em dois fatores com um app autenticador.",+ "manualEntry": "Ou insira esta chave manualmente:",+ "enable2fa": "Ativar 2FA",+ "disable2fa": "Desativar 2FA",+ "disable2faDescription": "Digite sua senha e um código de verificação para desativar a autenticação em dois fatores.",+ "twoFactorEnabled": "Autenticação em dois fatores ativada",+ "twoFactorDisabled": "Autenticação em dois fatores desativada"},"dashboard": {"title": "Painel",diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex 7d6910cb..641d4cab 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -8,10 +8,11 @@ import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'import { Card, CardContent, CardFooter } from '@/components/ui/card'import { ShellLogo } from '@/components/shell-logo'+import type { AxiosError } from 'axios'export default function LoginPage() {const { t } = useTranslation()- const { login, token } = useAuth()+ const { login, verify2fa, token } = useAuth()const navigate = useNavigate()const [email, setEmail] = useState('')const [password, setPassword] = useState('')@@ -19,6 +20,11 @@ export default function LoginPage() {const [isLoading, setIsLoading] = useState(false)const [registrationEnabled, setRegistrationEnabled] = useState(true)+ // 2FA state+ const [requires2fa, setRequires2fa] = useState(false)+ const [tempToken, setTempToken] = useState('')+ const [totpCode, setTotpCode] = useState('')+useEffect(() => {if (token) {navigate('/', { replace: true })@@ -39,15 +45,106 @@ export default function LoginPage() {setError('')setIsLoading(true)try {- await login(email, password)+ const result = await login(email, password)+ if (result.requires_2fa) {+ setRequires2fa(true)+ setTempToken(result.temp_token ?? '')+ } else {+ navigate('/')+ }+ } catch (err) {+ const axiosErr = err as AxiosError+ if (axiosErr?.response?.status === 429) {+ setError(t('auth.tooManyAttempts'))+ } else {+ setError(t('auth.invalidCredentials'))+ }+ } finally {+ setIsLoading(false)+ }+ }++ const handleVerify2fa = async (e: React.FormEvent) => {+ e.preventDefault()+ setError('')+ setIsLoading(true)+ try {+ await verify2fa(tempToken, totpCode)navigate('/')- } catch {- setError(t('auth.invalidCredentials'))+ } catch (err) {+ const axiosErr = err as AxiosError+ if (axiosErr?.response?.status === 401) {+ setError(t('auth.invalidCredentials'))+ // Token expired, go back to login+ setRequires2fa(false)+ setTempToken('')+ setTotpCode('')+ } else {+ setError(t('auth.invalid2faCode'))+ }} finally {setIsLoading(false)}}+ if (requires2fa) {+ return (+ <div className="flex flex-col items-center justify-center min-h-screen bg-background px-4">+ <Card className="w-full max-w-[380px] shadow-sm">+ <form onSubmit={handleVerify2fa}>+ <div className="flex flex-col items-center pt-8 pb-2 px-8">+ <div className="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center mb-4">+ <ShellLogo size={22} className="text-primary" />+ </div>+ <h1 className="text-xl font-semibold tracking-tight">{t('auth.twoFactor')}</h1>+ <p className="text-sm text-muted-foreground mt-1">{t('auth.twoFactorDescription')}</p>+ </div>+ <CardContent className="space-y-4 px-8 pt-4">+ {error && (+ <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-lg">+ {error}+ </div>+ )}+ <div className="space-y-1.5">+ <Label htmlFor="totp-code" className="text-sm">{t('auth.twoFactor')}</Label>+ <Input+ id="totp-code"+ type="text"+ inputMode="numeric"+ autoComplete="one-time-code"+ value={totpCode}+ onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}+ placeholder="000000"+ className="text-center text-lg tracking-[0.3em] font-mono"+ maxLength={6}+ required+ autoFocus+ />+ </div>+ </CardContent>+ <CardFooter className="flex flex-col gap-4 px-8 pb-8 pt-2">+ <Button type="submit" className="w-full" disabled={isLoading || totpCode.length !== 6}>+ {isLoading ? t('common.loading') : t('auth.verify')}+ </Button>+ <button+ type="button"+ onClick={() => {+ setRequires2fa(false)+ setTempToken('')+ setTotpCode('')+ setError('')+ }}+ className="text-sm text-muted-foreground hover:text-foreground"+ >+ {t('auth.login')}+ </button>+ </CardFooter>+ </form>+ </Card>+ </div>+ )+ }+return (<div className="flex flex-col items-center justify-center min-h-screen bg-background px-4"><Card className="w-full max-w-[380px] shadow-sm">diff --git a/frontend/src/pages/register.tsx b/frontend/src/pages/register.tsxindex 4b0e9275..da9074b3 100644--- a/frontend/src/pages/register.tsx+++ b/frontend/src/pages/register.tsx@@ -9,6 +9,7 @@ import { Label } from '@/components/ui/label'import { Card, CardContent, CardFooter } from '@/components/ui/card'import { ShellLogo } from '@/components/shell-logo'import { cn } from '@/lib/utils'+import type { AxiosError } from 'axios'const currencies = [{ code: 'USD', flag: '\u{1F1FA}\u{1F1F8}', symbol: '$' },@@ -60,8 +61,13 @@ export default function RegisterPage() {language: lang,})navigate('/')- } catch {- setError(t('auth.registrationError'))+ } catch (err) {+ const axiosErr = err as AxiosError+ if (axiosErr?.response?.status === 429) {+ setError(t('auth.tooManyAttempts'))+ } else {+ setError(t('auth.registrationError'))+ }} finally {setIsLoading(false)}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 67bb6b71..3fedd102 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -4,6 +4,7 @@ export interface User {is_active: booleanis_superuser: booleanis_verified: boolean+ is_2fa_enabled: booleanpreferences: UserPreferences}