Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix: harden user management with password validation, email uniqueness checks, and setting guards (#51)

Tássio Noronha4403d8fa3f43
diff --git a/backend/alembic/versions/020_app_settings.py b/backend/alembic/versions/020_app_settings.py
new file mode 100644
index 00000000..5e51fc14
--- /dev/null
+++ b/backend/alembic/versions/020_app_settings.py
@@ -0,0 +1,32 @@
+"""add app_settings table
+
+Revision ID: 020
+Revises: 019
+Create Date: 2026-04-02
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "020"
+down_revision: Union[str, None] = "019"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "app_settings",
+ sa.Column("key", sa.String(255), primary_key=True),
+ sa.Column("value", sa.String(2000), nullable=False),
+ )
+ # Seed default registration setting
+ op.execute(
+ "INSERT INTO app_settings (key, value) VALUES ('registration_enabled', 'true')"
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("app_settings")
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py
new file mode 100644
index 00000000..7e62b272
--- /dev/null
+++ b/backend/app/api/admin.py
@@ -0,0 +1,148 @@
+import uuid
+
+from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.auth import UserManager, current_superuser, get_user_manager
+from app.core.database import get_async_session
+from app.models.user import User
+from app.schemas.admin import (
+ AdminUserCreate,
+ AdminUserList,
+ AdminUserRead,
+ AdminUserUpdate,
+ AppSettingRead,
+ AppSettingUpdate,
+)
+from app.services import admin_service
+
+router = APIRouter(prefix="/api/admin", tags=["admin"])
+
+ALLOWED_SETTINGS = {"registration_enabled"}
+
+
[email protected]("/users", response_model=AdminUserList)
+async def list_users(
+ search: str = Query(None),
+ page: int = Query(1, ge=1),
+ limit: int = Query(50, ge=1, le=100),
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_superuser),
+):
+ users, total = await admin_service.list_users(session, search, page, limit)
+ return AdminUserList(
+ items=[AdminUserRead.model_validate(u) for u in users],
+ total=total,
+ )
+
+
[email protected]("/users", response_model=AdminUserRead, status_code=status.HTTP_201_CREATED)
+async def create_user(
+ data: AdminUserCreate,
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_superuser),
+ user_manager: UserManager = Depends(get_user_manager),
+):
+ try:
+ user = await admin_service.create_user(session, user_manager, data)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ return AdminUserRead.model_validate(user)
+
+
[email protected]("/users/{user_id}", response_model=AdminUserRead)
+async def get_user(
+ user_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_superuser),
+):
+ user = await admin_service.get_user(session, user_id)
+ if not user:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
+ return AdminUserRead.model_validate(user)
+
+
[email protected]("/users/{user_id}", response_model=AdminUserRead)
+async def update_user(
+ user_id: uuid.UUID,
+ data: AdminUserUpdate,
+ session: AsyncSession = Depends(get_async_session),
+ current_user: User = Depends(current_superuser),
+):
+ try:
+ user = await admin_service.update_user(session, user_id, data, current_user.id)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ if not user:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
+ return AdminUserRead.model_validate(user)
+
+
[email protected]("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_user(
+ user_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ current_user: User = Depends(current_superuser),
+):
+ try:
+ deleted = await admin_service.delete_user(session, user_id, current_user.id)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ if not deleted:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
+
+
[email protected]("/settings/{key}", response_model=AppSettingRead)
+async def get_setting(
+ key: str,
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_superuser),
+):
+ setting = await admin_service.get_app_setting(session, key)
+ if not setting:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Setting not found")
+ return AppSettingRead.model_validate(setting)
+
+
[email protected]("/settings/{key}", response_model=AppSettingRead)
+async def update_setting(
+ key: str,
+ data: AppSettingUpdate,
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_superuser),
+):
+ if key not in ALLOWED_SETTINGS:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"Setting '{key}' is not configurable",
+ )
+ SETTING_VALIDATORS = {
+ "registration_enabled": {"true", "false"},
+ }
+ if key in SETTING_VALIDATORS and data.value not in SETTING_VALIDATORS[key]:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"Invalid value for '{key}'. Allowed: {SETTING_VALIDATORS[key]}",
+ )
+ setting = await admin_service.set_app_setting(session, key, data.value)
+ return AppSettingRead.model_validate(setting)
+
+
[email protected]("/registration-status")
+async def registration_status(
+ session: AsyncSession = Depends(get_async_session),
+):
+ enabled = await admin_service.is_registration_enabled(session)
+ return {"enabled": enabled}
+
+
+async def check_registration_enabled(
+ request: Request,
+ session: AsyncSession = Depends(get_async_session),
+):
+ enabled = await admin_service.is_registration_enabled(session)
+ if not enabled:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Registration is currently disabled",
+ )
diff --git a/backend/app/core/auth.py b/backend/app/core/auth.py
index 5848bb07..bde23107 100644
--- a/backend/app/core/auth.py
+++ b/backend/app/core/auth.py
@@ -80,3 +80,4 @@ auth_backend = AuthenticationBackend(
fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])
current_active_user = fastapi_users.current_user(active=True)
+current_superuser = fastapi_users.current_user(active=True, superuser=True)
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 29837283..7bcd71c9 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -45,6 +45,9 @@ class Settings(BaseSettings):
storage_s3_secret_key: str = ""
storage_s3_endpoint_url: str = "" # for S3-compatible services (MinIO, DigitalOcean Spaces)
+ # Registration
+ registration_enabled: bool = True
+
# Celery
redis_url: str = "redis://localhost:6379/0"
diff --git a/backend/app/main.py b/backend/app/main.py
index 1a03b25e..6c0894b9 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -1,7 +1,7 @@
import logging
from contextlib import asynccontextmanager
-from fastapi import FastAPI
+from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.accounts import router as accounts_router
@@ -24,6 +24,7 @@ from app.api.attachments import router as attachments_router
from app.api.payees import router as payees_router
from app.api.settings import router as settings_router
from app.api.transactions import router as transactions_router
+from app.api.admin import router as admin_router, check_registration_enabled
from app.core.auth import auth_backend, fastapi_users
from app.core.config import get_settings
from app.schemas.user import UserCreate, UserRead, UserUpdate
@@ -70,6 +71,7 @@ app.include_router(
fastapi_users.get_register_router(UserRead, UserCreate),
prefix="/api/auth",
tags=["auth"],
+ dependencies=[Depends(check_registration_enabled)],
)
app.include_router(
fastapi_users.get_reset_password_router(),
@@ -103,6 +105,7 @@ app.include_router(export_router)
app.include_router(attachments_router)
app.include_router(payees_router)
app.include_router(settings_router)
+app.include_router(admin_router)
@app.get("/api/health")
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 306da326..7c284a4d 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -13,6 +13,7 @@ from app.models.asset_value import AssetValue
from app.models.fx_rate import FxRate
from app.models.transaction_attachment import TransactionAttachment
from app.models.payee import Payee, PayeeMapping
+from app.models.app_settings import AppSetting
__all__ = [
"User",
@@ -31,4 +32,5 @@ __all__ = [
"TransactionAttachment",
"Payee",
"PayeeMapping",
+ "AppSetting",
]
diff --git a/backend/app/models/app_settings.py b/backend/app/models/app_settings.py
new file mode 100644
index 00000000..15b54d69
--- /dev/null
+++ b/backend/app/models/app_settings.py
@@ -0,0 +1,11 @@
+from sqlalchemy import String
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.core.database import Base
+
+
+class AppSetting(Base):
+ __tablename__ = "app_settings"
+
+ key: Mapped[str] = mapped_column(String(255), primary_key=True)
+ value: Mapped[str] = mapped_column(String(2000))
diff --git a/backend/app/schemas/admin.py b/backend/app/schemas/admin.py
new file mode 100644
index 00000000..5231bcba
--- /dev/null
+++ b/backend/app/schemas/admin.py
@@ -0,0 +1,46 @@
+import uuid
+from typing import Optional
+
+from pydantic import BaseModel, ConfigDict, EmailStr, Field
+
+
+class AdminUserRead(BaseModel):
+ id: uuid.UUID
+ email: str
+ is_active: bool
+ is_superuser: bool
+ is_verified: bool
+ preferences: Optional[dict] = None
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class AdminUserCreate(BaseModel):
+ email: EmailStr
+ password: str = Field(min_length=8, max_length=72)
+ is_superuser: bool = False
+ preferences: Optional[dict] = None
+
+
+class AdminUserUpdate(BaseModel):
+ email: Optional[EmailStr] = None
+ password: Optional[str] = Field(None, min_length=8, max_length=72)
+ is_active: Optional[bool] = None
+ is_superuser: Optional[bool] = None
+ preferences: Optional[dict] = None
+
+
+class AdminUserList(BaseModel):
+ items: list[AdminUserRead]
+ total: int
+
+
+class AppSettingRead(BaseModel):
+ key: str
+ value: str
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class AppSettingUpdate(BaseModel):
+ value: str
diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.py
index 5d63ae7c..b58071d0 100644
--- a/backend/app/schemas/user.py
+++ b/backend/app/schemas/user.py
@@ -18,7 +18,7 @@ class UserRead(schemas.BaseUser[uuid.UUID]):
class UserCreate(schemas.BaseUserCreate):
- pass
+ preferences: Optional[dict] = None
class UserUpdate(schemas.BaseUserUpdate):
diff --git a/backend/app/services/admin_service.py b/backend/app/services/admin_service.py
new file mode 100644
index 00000000..f899fdd1
--- /dev/null
+++ b/backend/app/services/admin_service.py
@@ -0,0 +1,212 @@
+import uuid
+from typing import Optional
+
+from fastapi_users.exceptions import UserAlreadyExists
+from sqlalchemy import delete, func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.auth import UserManager
+from app.core.config import get_settings
+from app.models.app_settings import AppSetting
+from app.models.user import User
+from app.schemas.admin import AdminUserCreate, AdminUserUpdate
+
+
+async def list_users(
+ session: AsyncSession,
+ search: Optional[str] = None,
+ page: int = 1,
+ limit: int = 50,
+) -> tuple[list[User], int]:
+ query = select(User)
+ count_query = select(func.count()).select_from(User)
+
+ if search:
+ query = query.where(User.email.ilike(f"%{search}%"))
+ count_query = count_query.where(User.email.ilike(f"%{search}%"))
+
+ total = (await session.execute(count_query)).scalar() or 0
+
+ query = query.order_by(User.email).offset((page - 1) * limit).limit(limit)
+ result = await session.execute(query)
+ users = list(result.scalars().all())
+
+ return users, total
+
+
+async def get_user(session: AsyncSession, user_id: uuid.UUID) -> Optional[User]:
+ result = await session.execute(select(User).where(User.id == user_id))
+ return result.scalar_one_or_none()
+
+
+async def create_user(
+ session: AsyncSession,
+ user_manager: UserManager,
+ data: AdminUserCreate,
+) -> User:
+ from fastapi_users.schemas import BaseUserCreate
+
+ create_schema = BaseUserCreate(
+ email=data.email,
+ password=data.password,
+ is_superuser=data.is_superuser,
+ is_active=True,
+ is_verified=True,
+ )
+
+ try:
+ user = await user_manager.create(create_schema)
+ except UserAlreadyExists:
+ raise ValueError("A user with this email already exists")
+
+ # Set preferences if provided
+ if data.preferences:
+ user.preferences = data.preferences
+ session.add(user)
+ await session.commit()
+ await session.refresh(user)
+
+ return user
+
+
+async def update_user(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ data: AdminUserUpdate,
+ current_user_id: uuid.UUID,
+) -> Optional[User]:
+ user = await get_user(session, user_id)
+ if not user:
+ return None
+
+ # Self-protection: can't demote or deactivate self
+ if user_id == current_user_id:
+ if data.is_superuser is False:
+ raise ValueError("Cannot remove your own admin privileges")
+ if data.is_active is False:
+ raise ValueError("Cannot deactivate your own account")
+
+ if data.email is not None and data.email != user.email:
+ existing = await session.execute(
+ select(User).where(User.email == data.email)
+ )
+ if existing.scalar_one_or_none():
+ raise ValueError("A user with this email already exists")
+ user.email = data.email
+ if data.is_active is not None:
+ user.is_active = data.is_active
+ if data.is_superuser is not None:
+ user.is_superuser = data.is_superuser
+ if data.preferences is not None:
+ user.preferences = data.preferences
+ if data.password is not None:
+ from fastapi_users.password import PasswordHelper
+
+ password_helper = PasswordHelper()
+ user.hashed_password = password_helper.hash(data.password)
+
+ session.add(user)
+ await session.commit()
+ await session.refresh(user)
+ return user
+
+
+async def delete_user(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ current_user_id: uuid.UUID,
+) -> bool:
+ if user_id == current_user_id:
+ raise ValueError("Cannot delete your own account")
+
+ user = await get_user(session, user_id)
+ if not user:
+ return False
+
+ # Check last superuser protection
+ if user.is_superuser:
+ count_result = await session.execute(
+ select(func.count()).select_from(User).where(
+ User.is_superuser == True, # noqa: E712
+ User.is_active == True, # noqa: E712
+ )
+ )
+ superuser_count = count_result.scalar() or 0
+ if superuser_count <= 1:
+ raise ValueError("Cannot delete the last admin user")
+
+ # Cascade delete user data in correct order
+ from app.models.transaction_attachment import TransactionAttachment
+ from app.models.transaction import Transaction
+ from app.models.budget import Budget
+ from app.models.recurring_transaction import RecurringTransaction
+ from app.models.import_log import ImportLog
+ from app.models.rule import Rule
+ from app.models.asset_value import AssetValue
+ from app.models.asset import Asset
+ from app.models.payee import PayeeMapping, Payee
+ from app.models.account import Account
+ from app.models.category import Category
+ from app.models.category_group import CategoryGroup
+ from app.models.bank_connection import BankConnection
+
+ # Delete attachments for user's transactions
+ tx_ids_query = select(Transaction.id).where(Transaction.user_id == user_id)
+ await session.execute(
+ delete(TransactionAttachment).where(
+ TransactionAttachment.transaction_id.in_(tx_ids_query)
+ )
+ )
+
+ # Delete in dependency order
+ await session.execute(delete(Transaction).where(Transaction.user_id == user_id))
+ await session.execute(delete(Budget).where(Budget.user_id == user_id))
+ await session.execute(delete(RecurringTransaction).where(RecurringTransaction.user_id == user_id))
+ await session.execute(delete(ImportLog).where(ImportLog.user_id == user_id))
+ await session.execute(delete(Rule).where(Rule.user_id == user_id))
+
+ # Asset values depend on assets
+ asset_ids_query = select(Asset.id).where(Asset.user_id == user_id)
+ await session.execute(
+ delete(AssetValue).where(AssetValue.asset_id.in_(asset_ids_query))
+ )
+ await session.execute(delete(Asset).where(Asset.user_id == user_id))
+
+ await session.execute(delete(PayeeMapping).where(PayeeMapping.user_id == user_id))
+ await session.execute(delete(Payee).where(Payee.user_id == user_id))
+ await session.execute(delete(Account).where(Account.user_id == user_id))
+ await session.execute(delete(Category).where(Category.user_id == user_id))
+ await session.execute(delete(CategoryGroup).where(CategoryGroup.user_id == user_id))
+ await session.execute(delete(BankConnection).where(BankConnection.user_id == user_id))
+
+ # Delete the user
+ await session.delete(user)
+ await session.commit()
+ return True
+
+
+async def get_app_setting(session: AsyncSession, key: str) -> Optional[AppSetting]:
+ result = await session.execute(
+ select(AppSetting).where(AppSetting.key == key)
+ )
+ return result.scalar_one_or_none()
+
+
+async def set_app_setting(session: AsyncSession, key: str, value: str) -> AppSetting:
+ setting = await get_app_setting(session, key)
+ if setting:
+ setting.value = value
+ else:
+ setting = AppSetting(key=key, value=value)
+ session.add(setting)
+ await session.commit()
+ await session.refresh(setting)
+ return setting
+
+
+async def is_registration_enabled(session: AsyncSession) -> bool:
+ setting = await get_app_setting(session, "registration_enabled")
+ if setting:
+ return setting.value.lower() == "true"
+ # Fall back to env var
+ return get_settings().registration_enabled
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 682cbff0..d06b3bf9 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -22,6 +22,7 @@ from app.models.asset import Asset # noqa: F401
from app.models.asset_value import AssetValue # noqa: F401
from app.models.transaction_attachment import TransactionAttachment # noqa: F401
from app.models.payee import Payee, PayeeMapping # noqa: F401
+from app.models.app_settings import AppSetting # noqa: F401
# Use SQLite for tests — fast, no external dependency
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
@@ -137,6 +138,50 @@ def auth_headers(auth_token: str) -> dict:
return {"Authorization": f"Bearer {auth_token}"}
+@pytest_asyncio.fixture
+async def test_superuser(session: AsyncSession, clean_db) -> User:
+ """Create a test superuser (admin)."""
+ import bcrypt as _bcrypt
+
+ hashed = _bcrypt.hashpw(b"adminpass123", _bcrypt.gensalt()).decode()
+ user = User(
+ id=uuid.uuid4(),
+ hashed_password=hashed,
+ is_active=True,
+ is_superuser=True,
+ is_verified=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
+
+
+@pytest_asyncio.fixture
+async def admin_auth_token(client: AsyncClient, test_superuser: User) -> str:
+ """Get an auth token for the superuser."""
+ response = await client.post(
+ "/api/auth/login",
+ data={"username": "[email protected]", "password": "adminpass123"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ assert response.status_code == 200, f"Admin login failed: {response.text}"
+ return response.json()["access_token"]
+
+
+@pytest_asyncio.fixture
+def admin_auth_headers(admin_auth_token: str) -> dict:
+ """Auth headers for admin requests."""
+ return {"Authorization": f"Bearer {admin_auth_token}"}
+
+
@pytest_asyncio.fixture
async def test_categories(session: AsyncSession, test_user: User) -> list[Category]:
"""Create test categories."""
diff --git a/backend/tests/test_admin_api.py b/backend/tests/test_admin_api.py
new file mode 100644
index 00000000..d7eb7f9e
--- /dev/null
+++ b/backend/tests/test_admin_api.py
@@ -0,0 +1,350 @@
+import uuid
+
+import pytest
+
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.app_settings import AppSetting
+from app.models.user import User
+
+
+pytestmark = pytest.mark.asyncio
+
+
+class TestAdminUserCRUD:
+ """Test admin user CRUD operations."""
+
+ async def test_list_users_as_admin(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.get("/api/admin/users", headers=admin_auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert "items" in data
+ assert "total" in data
+ assert data["total"] >= 1
+ emails = [u["email"] for u in data["items"]]
+ assert "[email protected]" in emails
+
+ async def test_list_users_search(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.get(
+ "/api/admin/users", params={"search": "admin"}, headers=admin_auth_headers
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert all("admin" in u["email"] for u in data["items"])
+
+ async def test_create_user(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.post(
+ "/api/admin/users",
+ json={
+ "email": "[email protected]",
+ "password": "password123",
+ "is_superuser": False,
+ "preferences": {"language": "en", "currency_display": "USD"},
+ },
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["email"] == "[email protected]"
+ assert data["is_active"] is True
+ assert data["is_superuser"] is False
+
+ async def test_create_duplicate_user(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ # Create first
+ await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ # Try duplicate
+ response = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 400
+
+ async def test_get_user(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.get(
+ f"/api/admin/users/{test_superuser.id}", headers=admin_auth_headers
+ )
+ assert response.status_code == 200
+ assert response.json()["email"] == "[email protected]"
+
+ async def test_get_user_not_found(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ fake_id = uuid.uuid4()
+ response = await client.get(
+ f"/api/admin/users/{fake_id}", headers=admin_auth_headers
+ )
+ assert response.status_code == 404
+
+ async def test_update_user(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ # Create a user to update
+ create_resp = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ user_id = create_resp.json()["id"]
+
+ response = await client.patch(
+ f"/api/admin/users/{user_id}",
+ json={"is_active": False},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["is_active"] is False
+
+ async def test_delete_user(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ # Create a user to delete
+ create_resp = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ user_id = create_resp.json()["id"]
+
+ response = await client.delete(
+ f"/api/admin/users/{user_id}", headers=admin_auth_headers
+ )
+ assert response.status_code == 204
+
+ # Verify deleted
+ get_resp = await client.get(
+ f"/api/admin/users/{user_id}", headers=admin_auth_headers
+ )
+ assert get_resp.status_code == 404
+
+ async def test_update_user_email_conflict(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ # Create two users
+ resp_a = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ user_a_id = resp_a.json()["id"]
+
+ # Try to update user A's email to user B's email
+ response = await client.patch(
+ f"/api/admin/users/{user_a_id}",
+ json={"email": "[email protected]"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 400
+ assert "email already exists" in response.json()["detail"].lower()
+
+ async def test_update_user_password(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ # Create a user
+ create_resp = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "oldpassword123"},
+ headers=admin_auth_headers,
+ )
+ user_id = create_resp.json()["id"]
+
+ # Update the password
+ response = await client.patch(
+ f"/api/admin/users/{user_id}",
+ json={"password": "newpassword456"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 200
+
+ # Login with the new password
+ login_resp = await client.post(
+ "/api/auth/login",
+ data={"username": "[email protected]", "password": "newpassword456"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ assert login_resp.status_code == 200
+ assert "access_token" in login_resp.json()
+
+ async def test_update_user_password_too_short(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ # Create a user
+ create_resp = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin_auth_headers,
+ )
+ user_id = create_resp.json()["id"]
+
+ # Try to update with a too-short password
+ response = await client.patch(
+ f"/api/admin/users/{user_id}",
+ json={"password": "short"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 422
+
+
+class TestAdminProtections:
+ """Test access control and self-protection."""
+
+ async def test_non_admin_gets_403(self, client: AsyncClient, auth_headers: dict, test_user: User):
+ response = await client.get("/api/admin/users", headers=auth_headers)
+ assert response.status_code == 403
+
+ async def test_unauthenticated_gets_401(self, client: AsyncClient):
+ response = await client.get("/api/admin/users")
+ assert response.status_code == 401
+
+ async def test_cannot_delete_self(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.delete(
+ f"/api/admin/users/{test_superuser.id}", headers=admin_auth_headers
+ )
+ assert response.status_code == 400
+ assert "own account" in response.json()["detail"].lower()
+
+ async def test_cannot_demote_self(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.patch(
+ f"/api/admin/users/{test_superuser.id}",
+ json={"is_superuser": False},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 400
+ assert "own admin" in response.json()["detail"].lower()
+
+ async def test_cannot_deactivate_self(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.patch(
+ f"/api/admin/users/{test_superuser.id}",
+ json={"is_active": False},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 400
+ assert "own account" in response.json()["detail"].lower()
+
+ async def test_cannot_delete_last_superuser(
+ self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User
+ ):
+ # Create a second superuser and login as them
+ create_resp = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "adminpass456", "is_superuser": True},
+ headers=admin_auth_headers,
+ )
+ assert create_resp.status_code == 201
+
+ # Login as admin2
+ login_resp = await client.post(
+ "/api/auth/login",
+ data={"username": "[email protected]", "password": "adminpass456"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ assert login_resp.status_code == 200
+ admin2_headers = {"Authorization": f"Bearer {login_resp.json()['access_token']}"}
+
+ # admin2 deletes admin1 — should succeed because admin2 still exists
+ response = await client.delete(
+ f"/api/admin/users/{test_superuser.id}", headers=admin2_headers
+ )
+ assert response.status_code == 204
+
+ # Now create a non-admin user
+ create_resp2 = await client.post(
+ "/api/admin/users",
+ json={"email": "[email protected]", "password": "password123"},
+ headers=admin2_headers,
+ )
+ assert create_resp2.status_code == 201
+ assert create_resp2.json()["id"]
+
+ # admin2 is now the only superuser — trying to delete them from another session
+ # would fail with self-protection. Instead, test that deleting regular user works
+ # but the last-superuser logic is intact by checking the count.
+ # We can't easily test deleting the last superuser without self-protection kicking in,
+ # but we verified above that deleting a superuser when another exists succeeds.
+
+
+class TestRegistrationToggle:
+ """Test the registration toggle functionality."""
+
+ async def test_registration_status_public(self, client: AsyncClient):
+ """Registration status endpoint should work without auth."""
+ response = await client.get("/api/admin/registration-status")
+ assert response.status_code == 200
+ assert "enabled" in response.json()
+
+ async def test_disable_registration(
+ self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User, session: AsyncSession
+ ):
+ # Seed the setting if not exists
+ setting = AppSetting(key="registration_enabled", value="true")
+ session.add(setting)
+ await session.commit()
+
+ # Disable registration
+ response = await client.patch(
+ "/api/admin/settings/registration_enabled",
+ json={"value": "false"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["value"] == "false"
+
+ # Verify registration is blocked
+ reg_response = await client.post(
+ "/api/auth/register",
+ json={"email": "[email protected]", "password": "password123"},
+ )
+ assert reg_response.status_code == 403
+
+ # Re-enable for other tests
+ await client.patch(
+ "/api/admin/settings/registration_enabled",
+ json={"value": "true"},
+ headers=admin_auth_headers,
+ )
+
+ async def test_enable_registration(
+ self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User, session: AsyncSession
+ ):
+ # Ensure enabled
+ setting = AppSetting(key="registration_enabled", value="true")
+ await session.merge(setting)
+ await session.commit()
+
+ response = await client.get("/api/admin/registration-status")
+ assert response.status_code == 200
+ assert response.json()["enabled"] is True
+
+ async def test_setting_not_configurable(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.patch(
+ "/api/admin/settings/some_random_key",
+ json={"value": "test"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 400
+
+ async def test_get_setting(
+ self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User, session: AsyncSession
+ ):
+ setting = AppSetting(key="registration_enabled", value="true")
+ await session.merge(setting)
+ await session.commit()
+
+ response = await client.get(
+ "/api/admin/settings/registration_enabled", headers=admin_auth_headers
+ )
+ assert response.status_code == 200
+ assert response.json()["key"] == "registration_enabled"
+
+ async def test_get_setting_not_found(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.get(
+ "/api/admin/settings/nonexistent", headers=admin_auth_headers
+ )
+ assert response.status_code == 404
+
+ async def test_setting_invalid_value(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):
+ response = await client.patch(
+ "/api/admin/settings/registration_enabled",
+ json={"value": "maybe"},
+ headers=admin_auth_headers,
+ )
+ assert response.status_code == 400
+ assert "invalid value" in response.json()["detail"].lower()
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index a0423557..5aaaad52 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -5,6 +5,7 @@ import { Toaster } from '@/components/ui/sonner'
import { ThemeProvider } from '@/components/theme-provider'
import { AuthProvider } from '@/contexts/auth-context'
import { ProtectedRoute } from '@/components/protected-route'
+import { AdminRoute } from '@/components/admin-route'
import { AppLayout } from '@/components/app-layout'
const SetupPage = lazy(() => import('@/pages/setup'))
@@ -22,6 +23,7 @@ const RecurringPage = lazy(() => import('@/pages/recurring'))
const AssetsPage = lazy(() => import('@/pages/assets'))
const ReportsPage = lazy(() => import('@/pages/reports'))
const PayeesPage = lazy(() => import('@/pages/payees'))
+const AdminSettingsPage = lazy(() => import('@/pages/admin/settings'))
const queryClient = new QueryClient({
defaultOptions: {
@@ -70,6 +72,7 @@ function App() {
<Route path="/assets" element={<AssetsPage />} />
<Route path="/reports" element={<ReportsPage />} />
<Route path="/payees" element={<PayeesPage />} />
+ <Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} />
</Route>
</Routes>
</Suspense>
diff --git a/frontend/src/components/admin-route.tsx b/frontend/src/components/admin-route.tsx
new file mode 100644
index 00000000..ac8346fd
--- /dev/null
+++ b/frontend/src/components/admin-route.tsx
@@ -0,0 +1,20 @@
+import { Navigate } from 'react-router-dom'
+import { useAuth } from '@/contexts/auth-context'
+
+export function AdminRoute({ children }: { children: React.ReactNode }) {
+ const { token, user, isLoading } = useAuth()
+
+ if (isLoading) {
+ return (
+ <div className="flex items-center justify-center min-h-screen">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
+ </div>
+ )
+ }
+
+ if (!token || !user?.is_superuser) {
+ return <Navigate to="/" replace />
+ }
+
+ return <>{children}</>
+}
diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsx
index 8e13909d..c7f644d9 100644
--- a/frontend/src/components/app-layout.tsx
+++ b/frontend/src/components/app-layout.tsx
@@ -1,5 +1,5 @@
import { useState, useCallback } from 'react'
-import { Link, Outlet, useLocation } from 'react-router-dom'
+import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { useAuth } from '@/contexts/auth-context'
@@ -40,6 +40,7 @@ import {
Moon,
KeyRound,
HardDriveDownload,
+ Shield,
} from 'lucide-react'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { ChangePasswordDialog } from '@/components/change-password-dialog'
@@ -76,6 +77,7 @@ export function AppLayout() {
const locale = i18n.language === 'en' ? 'en-US' : i18n.language
const { theme, setTheme } = useTheme()
const location = useLocation()
+ const navigate = useNavigate()
const [sidebarOpen, setSidebarOpen] = useState(false)
const [accountsExpanded, setAccountsExpanded] = useState(true)
const { privacyMode, togglePrivacyMode, mask } = usePrivacyMode()
@@ -141,7 +143,7 @@ export function AppLayout() {
} finally {
setBackingUp(false)
}
- }} dark />
+ }} dark isAdmin={user?.is_superuser} />
</div>
</header>
@@ -347,6 +349,18 @@ export function AppLayout() {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48" side="top">
+ {user?.is_superuser && (
+ <>
+ <DropdownMenuItem
+ onClick={() => navigate('/admin')}
+ className="flex items-center gap-2"
+ >
+ <Shield size={14} />
+ {t('nav.groupAdmin')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
<DropdownMenuItem
onClick={() => setChangePasswordOpen(true)}
className="flex items-center gap-2"
@@ -399,8 +413,9 @@ export function AppLayout() {
)
}
-function UserMenu({ userInitial, logout, onChangePassword, onBackup, backingUp, dark }: { userInitial: string; logout: () => void; onChangePassword: () => void; onBackup: () => void; backingUp: boolean; dark?: boolean }) {
+function UserMenu({ userInitial, logout, onChangePassword, onBackup, backingUp, dark, isAdmin }: { userInitial: string; logout: () => void; onChangePassword: () => void; onBackup: () => void; backingUp: boolean; dark?: boolean; isAdmin?: boolean }) {
const { t } = useTranslation()
+ const nav = useNavigate()
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -413,6 +428,15 @@ function UserMenu({ userInitial, logout, onChangePassword, onBackup, backingUp,
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ {isAdmin && (
+ <>
+ <DropdownMenuItem onClick={() => nav('/admin')} className="flex items-center gap-2">
+ <Shield size={14} />
+ {t('nav.groupAdmin')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
<DropdownMenuItem onClick={onChangePassword} className="flex items-center gap-2">
<KeyRound size={14} />
{t('auth.changePassword')}
diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-context.tsx
index d94aad90..712a3115 100644
--- a/frontend/src/contexts/auth-context.tsx
+++ b/frontend/src/contexts/auth-context.tsx
@@ -9,7 +9,7 @@ interface AuthContextType {
isLoading: boolean
login: (email: string, password: string) => Promise<void>
loginWithToken: (accessToken: string) => void
- register: (email: string, password: string) => Promise<void>
+ register: (email: string, password: string, preferences?: Record<string, string>) => Promise<void>
updateUser: (user: User) => void
logout: () => void
}
@@ -67,8 +67,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setUser(updatedUser)
}, [])
- const register = useCallback(async (email: string, password: string) => {
- await auth.register(email, password)
+ const register = useCallback(async (email: string, password: string, preferences?: Record<string, string>) => {
+ await auth.register(email, password, preferences)
await login(email, password)
}, [login])
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 9c470319..410346be 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1,6 +1,9 @@
import axios from 'axios'
import type {
User,
+ AdminUser,
+ AdminUserList,
+ AppSetting,
Category,
CategoryGroup,
BankConnection,
@@ -75,8 +78,8 @@ export const auth = {
})
return data
},
- register: async (email: string, password: string) => {
- const { data } = await api.post('/auth/register', { email, password })
+ register: async (email: string, password: string, preferences?: Record<string, string>) => {
+ const { data } = await api.post('/auth/register', { email, password, preferences })
return data
},
me: async (): Promise<User> => {
@@ -570,4 +573,39 @@ export const backup = {
},
}
+// Admin
+export const admin = {
+ listUsers: async (params?: { search?: string; page?: number; limit?: number }): Promise<AdminUserList> => {
+ const { data } = await api.get('/admin/users', { params })
+ return data
+ },
+ getUser: async (id: string): Promise<AdminUser> => {
+ const { data } = await api.get(`/admin/users/${id}`)
+ return data
+ },
+ createUser: async (user: { email: string; password: string; is_superuser?: boolean; preferences?: Record<string, unknown> }): Promise<AdminUser> => {
+ const { data } = await api.post('/admin/users', user)
+ return data
+ },
+ updateUser: async (id: string, user: Partial<{ email: string; password: string; is_active: boolean; is_superuser: boolean; preferences: Record<string, unknown> }>): Promise<AdminUser> => {
+ const { data } = await api.patch(`/admin/users/${id}`, user)
+ return data
+ },
+ deleteUser: async (id: string): Promise<void> => {
+ await api.delete(`/admin/users/${id}`)
+ },
+ getSetting: async (key: string): Promise<AppSetting> => {
+ const { data } = await api.get(`/admin/settings/${key}`)
+ return data
+ },
+ updateSetting: async (key: string, value: string): Promise<AppSetting> => {
+ const { data } = await api.patch(`/admin/settings/${key}`, { value })
+ return data
+ },
+ registrationStatus: async (): Promise<{ enabled: boolean }> => {
+ const { data } = await api.get('/admin/registration-status')
+ return data
+ },
+}
+
export default api
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 74ff3dff..b656fba5 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -17,7 +17,8 @@
"reports": "Reports",
"groupAnalysis": "Analysis",
"groupSetup": "Setup",
- "groupAccounts": "Accounts"
+ "groupAccounts": "Accounts",
+ "groupAdmin": "Administration"
},
"auth": {
"login": "Login",
@@ -39,7 +40,9 @@
"passwordChangeError": "Failed to change password",
"confirmPassword": "Confirm password",
"passwordMismatch": "Passwords do not match",
- "registrationError": "Error creating account. Please try again."
+ "registrationError": "Error creating account. Please try again.",
+ "registerDescription": "Create your account to get started",
+ "currency": "Currency"
},
"dashboard": {
"title": "Dashboard",
@@ -581,6 +584,41 @@
"success": "Backup downloaded successfully",
"error": "Failed to download backup"
},
+ "admin": {
+ "users": {
+ "title": "User Management",
+ "searchPlaceholder": "Search users...",
+ "add": "Add User",
+ "edit": "Edit User",
+ "email": "Email",
+ "status": "Status",
+ "role": "Role",
+ "active": "Active",
+ "inactive": "Inactive",
+ "admin": "Admin",
+ "user": "User",
+ "you": "You",
+ "empty": "No users found",
+ "created": "User created",
+ "updated": "User updated",
+ "deleted": "User deleted",
+ "confirmDeleteTitle": "Delete user?",
+ "confirmDeleteDesc": "This will permanently delete the user {{email}} and all their data. This action cannot be undone.",
+ "resetPassword": "Reset password",
+ "resetPasswordPlaceholder": "Leave blank to keep current",
+ "addDesc": "Create a new user account with access to the application.",
+ "adminRole": "Administrator privileges",
+ "enabled": "On",
+ "disabled": "Off"
+ },
+ "settings": {
+ "title": "Admin Settings",
+ "registrationTitle": "Registration",
+ "registration": "Allow user registration",
+ "registrationDesc": "When disabled, only admins can create new user accounts.",
+ "updated": "Setting updated"
+ }
+ },
"onboarding": {
"sidebar": "Sidebar Navigation",
"sidebarDesc": "Use the sidebar to navigate between sections of the app.",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 95415004..9e6ede8c 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -17,7 +17,8 @@
"reports": "Relatórios",
"groupAnalysis": "Análise",
"groupSetup": "Configuração",
- "groupAccounts": "Contas"
+ "groupAccounts": "Contas",
+ "groupAdmin": "Administração"
},
"auth": {
"login": "Entrar",
@@ -39,7 +40,9 @@
"passwordChangeError": "Erro ao alterar a senha",
"confirmPassword": "Confirmar senha",
"passwordMismatch": "As senhas não conferem",
- "registrationError": "Erro ao criar conta. Tente novamente."
+ "registrationError": "Erro ao criar conta. Tente novamente.",
+ "registerDescription": "Crie sua conta para começar",
+ "currency": "Moeda"
},
"dashboard": {
"title": "Painel",
@@ -581,6 +584,41 @@
"success": "Backup baixado com sucesso",
"error": "Erro ao baixar backup"
},
+ "admin": {
+ "users": {
+ "title": "Gerenciamento de Usuários",
+ "searchPlaceholder": "Buscar usuários...",
+ "add": "Adicionar Usuário",
+ "edit": "Editar Usuário",
+ "email": "E-mail",
+ "status": "Status",
+ "role": "Função",
+ "active": "Ativo",
+ "inactive": "Inativo",
+ "admin": "Admin",
+ "user": "Usuário",
+ "you": "Você",
+ "empty": "Nenhum usuário encontrado",
+ "created": "Usuário criado",
+ "updated": "Usuário atualizado",
+ "deleted": "Usuário excluído",
+ "confirmDeleteTitle": "Excluir usuário?",
+ "confirmDeleteDesc": "Isso excluirá permanentemente o usuário {{email}} e todos os seus dados. Esta ação não pode ser desfeita.",
+ "resetPassword": "Redefinir senha",
+ "resetPasswordPlaceholder": "Deixe em branco para manter a atual",
+ "addDesc": "Criar uma nova conta de usuário com acesso ao aplicativo.",
+ "adminRole": "Privilégios de administrador",
+ "enabled": "Sim",
+ "disabled": "Não"
+ },
+ "settings": {
+ "title": "Configurações Admin",
+ "registrationTitle": "Registro",
+ "registration": "Permitir registro de usuários",
+ "registrationDesc": "Quando desativado, apenas admins podem criar novas contas.",
+ "updated": "Configuração atualizada"
+ }
+ },
"onboarding": {
"sidebar": "Navegação Lateral",
"sidebarDesc": "Use a barra lateral para navegar entre as seções do app.",
diff --git a/frontend/src/pages/admin/settings.tsx b/frontend/src/pages/admin/settings.tsx
new file mode 100644
index 00000000..0f21a1d6
--- /dev/null
+++ b/frontend/src/pages/admin/settings.tsx
@@ -0,0 +1,442 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { admin as adminApi } from '@/lib/api'
+import { useAuth } from '@/contexts/auth-context'
+import { toast } from 'sonner'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Badge } from '@/components/ui/badge'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Avatar, AvatarFallback } from '@/components/ui/avatar'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogFooter,
+ DialogDescription,
+} from '@/components/ui/dialog'
+import { PageHeader } from '@/components/page-header'
+import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users } from 'lucide-react'
+import type { AdminUser } from '@/types'
+
+export default function AdminSettingsPage() {
+ const { t } = useTranslation()
+ const { user: currentUser } = useAuth()
+ const queryClient = useQueryClient()
+
+ const [search, setSearch] = useState('')
+ const [createOpen, setCreateOpen] = useState(false)
+ const [editUser, setEditUser] = useState<AdminUser | null>(null)
+ const [deleteUser, setDeleteUser] = useState<AdminUser | null>(null)
+
+ const [formEmail, setFormEmail] = useState('')
+ const [formPassword, setFormPassword] = useState('')
+ const [formIsAdmin, setFormIsAdmin] = useState(false)
+ const [formLanguage, setFormLanguage] = useState('en')
+ const [formCurrency, setFormCurrency] = useState('USD')
+
+ const [editEmail, setEditEmail] = useState('')
+ const [editIsActive, setEditIsActive] = useState(true)
+ const [editIsAdmin, setEditIsAdmin] = useState(false)
+ const [editPassword, setEditPassword] = useState('')
+ const [showPasswordField, setShowPasswordField] = useState(false)
+
+ const { data: usersData, isLoading: usersLoading } = useQuery({
+ queryKey: ['admin', 'users', search],
+ queryFn: () => adminApi.listUsers({ search: search || undefined }),
+ })
+
+ const createMutation = useMutation({
+ mutationFn: (data: { email: string; password: string; is_superuser: boolean; preferences: Record<string, unknown> }) =>
+ adminApi.createUser(data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['admin', 'users'] })
+ setCreateOpen(false)
+ resetCreateForm()
+ toast.success(t('admin.users.created'))
+ },
+ onError: (err: { response?: { data?: { detail?: string } } }) => {
+ toast.error(err.response?.data?.detail || t('common.error'))
+ },
+ })
+
+ const updateMutation = useMutation({
+ mutationFn: ({ id, ...data }: { id: string } & Record<string, unknown>) =>
+ adminApi.updateUser(id, data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['admin', 'users'] })
+ setEditUser(null)
+ toast.success(t('admin.users.updated'))
+ },
+ onError: (err: { response?: { data?: { detail?: string } } }) => {
+ toast.error(err.response?.data?.detail || t('common.error'))
+ },
+ })
+
+ const deleteMutation = useMutation({
+ mutationFn: (id: string) => adminApi.deleteUser(id),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['admin', 'users'] })
+ setDeleteUser(null)
+ toast.success(t('admin.users.deleted'))
+ },
+ onError: (err: { response?: { data?: { detail?: string } } }) => {
+ toast.error(err.response?.data?.detail || t('common.error'))
+ },
+ })
+
+ const { data: regSetting, isLoading: settingsLoading } = useQuery({
+ queryKey: ['admin', 'settings', 'registration_enabled'],
+ queryFn: () => adminApi.getSetting('registration_enabled'),
+ })
+
+ const updateSettingMutation = useMutation({
+ mutationFn: (value: string) => adminApi.updateSetting('registration_enabled', value),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['admin', 'settings'] })
+ toast.success(t('admin.settings.updated'))
+ },
+ onError: () => {
+ toast.error(t('common.error'))
+ },
+ })
+
+ function resetCreateForm() {
+ setFormEmail('')
+ setFormPassword('')
+ setFormIsAdmin(false)
+ setFormLanguage('en')
+ setFormCurrency('USD')
+ }
+
+ function openEdit(u: AdminUser) {
+ setEditUser(u)
+ setEditEmail(u.email)
+ setEditIsActive(u.is_active)
+ setEditIsAdmin(u.is_superuser)
+ setEditPassword('')
+ setShowPasswordField(false)
+ }
+
+ const users = usersData?.items ?? []
+ const isSelf = (u: AdminUser) => u.id === currentUser?.id
+ const isEnabled = regSetting?.value === 'true'
+
+ const filteredUsers = users
+
+ return (
+ <div>
+ <PageHeader
+ section={t('nav.groupAdmin')}
+ title={t('admin.settings.title')}
+ action={
+ <Button onClick={() => { resetCreateForm(); setCreateOpen(true) }}>
+ <Plus size={16} className="mr-1.5" />
+ {t('admin.users.add')}
+ </Button>
+ }
+ />
+
+ {/* Search */}
+ <div className="relative max-w-md mb-5">
+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('admin.users.searchPlaceholder')}
+ className="pl-9 h-10 bg-card border-border/60 rounded-xl"
+ />
+ </div>
+
+ {/* User list */}
+ <div className="rounded-xl border border-border/60 bg-card overflow-hidden mb-8">
+ {usersLoading ? (
+ <div className="p-4 space-y-3">
+ {[...Array(3)].map((_, i) => <Skeleton key={i} className="h-14 w-full rounded-lg" />)}
+ </div>
+ ) : filteredUsers.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
+ <Users size={32} className="mb-3 opacity-40" />
+ <p className="text-sm">{t('admin.users.empty')}</p>
+ </div>
+ ) : (
+ <div className="divide-y divide-border/40">
+ {filteredUsers.map((u) => (
+ <button
+ key={u.id}
+ onClick={() => openEdit(u)}
+ className="flex items-center gap-4 w-full px-5 py-3.5 text-left hover:bg-muted/40 transition-colors"
+ >
+ <Avatar className="h-9 w-9 shrink-0">
+ <AvatarFallback className={u.is_superuser ? 'bg-primary/15 text-primary text-xs font-semibold' : 'bg-muted text-muted-foreground text-xs font-semibold'}>
+ {u.email.charAt(0).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-foreground truncate">{u.email}</span>
+ {isSelf(u) && (
+ <span className="text-[10px] font-medium text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
+ {t('admin.users.you')}
+ </span>
+ )}
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {u.is_superuser ? t('admin.users.admin') : t('admin.users.user')}
+ </span>
+ </div>
+
+ <div className="flex items-center gap-2 shrink-0">
+ {!u.is_active && (
+ <Badge variant="secondary" className="text-[10px] font-medium">
+ {t('admin.users.inactive')}
+ </Badge>
+ )}
+ {u.is_superuser && (
+ <Shield size={14} className="text-primary" />
+ )}
+ {!isSelf(u) && (
+ <span
+ role="button"
+ onClick={(e) => { e.stopPropagation(); setDeleteUser(u) }}
+ className="p-1.5 rounded-md text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors"
+ >
+ <Trash2 size={14} />
+ </span>
+ )}
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Settings section */}
+ <div className="rounded-xl border border-border/60 bg-card overflow-hidden">
+ <div className="px-5 py-4 border-b border-border/40">
+ <div className="flex items-center gap-2 mb-0.5">
+ <UserCog size={15} className="text-muted-foreground" />
+ <h3 className="text-sm font-semibold text-foreground">{t('admin.settings.registrationTitle')}</h3>
+ </div>
+ </div>
+
+ {settingsLoading ? (
+ <div className="p-5">
+ <Skeleton className="h-8 w-48" />
+ </div>
+ ) : (
+ <div className="px-5 py-4 flex items-center justify-between">
+ <div>
+ <p className="text-sm text-foreground">{t('admin.settings.registration')}</p>
+ <p className="text-xs text-muted-foreground mt-0.5">{t('admin.settings.registrationDesc')}</p>
+ </div>
+ <button
+ onClick={() => updateSettingMutation.mutate(isEnabled ? 'false' : 'true')}
+ disabled={updateSettingMutation.isPending}
+ className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${isEnabled ? 'bg-primary' : 'bg-muted-foreground/20'}`}
+ >
+ <span
+ className={`pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow-sm transition-transform ${isEnabled ? 'translate-x-6' : 'translate-x-1'}`}
+ />
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Create User Dialog */}
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('admin.users.add')}</DialogTitle>
+ <DialogDescription>{t('admin.users.addDesc')}</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={(e) => {
+ e.preventDefault()
+ createMutation.mutate({
+ email: formEmail,
+ password: formPassword,
+ is_superuser: formIsAdmin,
+ preferences: { language: formLanguage, currency_display: formCurrency },
+ })
+ }}>
+ <div className="space-y-4 py-2">
+ <div className="space-y-1.5">
+ <Label className="text-[13px]">{t('admin.users.email')}</Label>
+ <Input type="email" value={formEmail} onChange={(e) => setFormEmail(e.target.value)} required className="h-10 rounded-lg" placeholder="[email protected]" />
+ </div>
+ <div className="space-y-1.5">
+ <Label className="text-[13px]">{t('auth.password')}</Label>
+ <Input type="password" value={formPassword} onChange={(e) => setFormPassword(e.target.value)} required minLength={8} className="h-10 rounded-lg" />
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1.5">
+ <Label className="text-[13px]">{t('setup.language')}</Label>
+ <select
+ value={formLanguage}
+ onChange={(e) => setFormLanguage(e.target.value)}
+ className="w-full h-10 rounded-lg border border-input bg-background px-3 text-sm"
+ >
+ <option value="en">English</option>
+ <option value="pt-BR">Português (BR)</option>
+ </select>
+ </div>
+ <div className="space-y-1.5">
+ <Label className="text-[13px]">{t('setup.currency')}</Label>
+ <Input value={formCurrency} onChange={(e) => setFormCurrency(e.target.value)} className="h-10 rounded-lg" />
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setFormIsAdmin(!formIsAdmin)}
+ className={`flex items-center gap-2 w-full px-3.5 py-2.5 rounded-lg border text-sm font-medium transition-all ${formIsAdmin ? 'bg-primary/8 border-primary/30 text-primary' : 'border-border text-muted-foreground hover:border-border/80'}`}
+ >
+ {formIsAdmin ? <Shield size={15} /> : <ShieldOff size={15} />}
+ <span className="flex-1 text-left">{t('admin.users.adminRole')}</span>
+ <span className={`text-xs ${formIsAdmin ? 'text-primary' : 'text-muted-foreground/60'}`}>
+ {formIsAdmin ? t('admin.users.enabled') : t('admin.users.disabled')}
+ </span>
+ </button>
+ </div>
+ <DialogFooter className="mt-4">
+ <Button variant="outline" type="button" onClick={() => setCreateOpen(false)} className="rounded-lg">
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={createMutation.isPending} className="rounded-lg">
+ {createMutation.isPending ? t('common.loading') : t('common.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ {/* Edit User Dialog */}
+ <Dialog open={!!editUser} onOpenChange={(open) => !open && setEditUser(null)}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('admin.users.edit')}</DialogTitle>
+ </DialogHeader>
+ {editUser && (
+ <form onSubmit={(e) => {
+ e.preventDefault()
+ const updates: Record<string, unknown> = { id: editUser.id }
+ if (editEmail !== editUser.email) updates.email = editEmail
+ if (editIsActive !== editUser.is_active) updates.is_active = editIsActive
+ if (editIsAdmin !== editUser.is_superuser) updates.is_superuser = editIsAdmin
+ if (editPassword && editPassword.length >= 8) updates.password = editPassword
+ updateMutation.mutate(updates as { id: string })
+ }}>
+ <div className="space-y-4 py-2">
+ <div className="flex items-center gap-3 pb-2">
+ <Avatar className="h-10 w-10">
+ <AvatarFallback className={editUser.is_superuser ? 'bg-primary/15 text-primary font-semibold' : 'bg-muted text-muted-foreground font-semibold'}>
+ {editUser.email.charAt(0).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <p className="text-sm font-medium">{editUser.email}</p>
+ <p className="text-xs text-muted-foreground">
+ {editUser.is_superuser ? t('admin.users.admin') : t('admin.users.user')}
+ {isSelf(editUser) && ` — ${t('admin.users.you')}`}
+ </p>
+ </div>
+ </div>
+
+ <div className="space-y-1.5">
+ <Label className="text-[13px]">{t('admin.users.email')}</Label>
+ <Input type="email" value={editEmail} onChange={(e) => setEditEmail(e.target.value)} required autoComplete="off" className="h-10 rounded-lg" />
+ </div>
+ {showPasswordField ? (
+ <div className="space-y-1.5">
+ <Label className="text-[13px]">{t('admin.users.resetPassword')}</Label>
+ <Input
+ type="text"
+ value={editPassword}
+ onChange={(e) => setEditPassword(e.target.value)}
+ placeholder={t('admin.users.resetPasswordPlaceholder')}
+ minLength={8}
+ maxLength={72}
+ autoComplete="off"
+ autoFocus
+ className="h-10 rounded-lg"
+ />
+ </div>
+ ) : (
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full rounded-lg"
+ onClick={() => setShowPasswordField(true)}
+ >
+ {t('admin.users.resetPassword')}
+ </Button>
+ )}
+
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => !isSelf(editUser) && setEditIsActive(!editIsActive)}
+ disabled={isSelf(editUser)}
+ className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border text-sm font-medium transition-all ${
+ isSelf(editUser) ? 'opacity-50 cursor-not-allowed' : ''
+ } ${editIsActive ? 'bg-emerald-500/8 border-emerald-500/30 text-emerald-600' : 'border-border text-muted-foreground'}`}
+ >
+ <span className={`h-2 w-2 rounded-full ${editIsActive ? 'bg-emerald-500' : 'bg-muted-foreground/30'}`} />
+ {editIsActive ? t('admin.users.active') : t('admin.users.inactive')}
+ </button>
+ <button
+ type="button"
+ onClick={() => !isSelf(editUser) && setEditIsAdmin(!editIsAdmin)}
+ disabled={isSelf(editUser)}
+ className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border text-sm font-medium transition-all ${
+ isSelf(editUser) ? 'opacity-50 cursor-not-allowed' : ''
+ } ${editIsAdmin ? 'bg-primary/8 border-primary/30 text-primary' : 'border-border text-muted-foreground'}`}
+ >
+ {editIsAdmin ? <Shield size={14} /> : <ShieldOff size={14} />}
+ {t('admin.users.admin')}
+ </button>
+ </div>
+ </div>
+ <DialogFooter className="mt-4">
+ <Button variant="outline" type="button" onClick={() => setEditUser(null)} className="rounded-lg">
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={updateMutation.isPending} className="rounded-lg">
+ {updateMutation.isPending ? t('common.loading') : t('common.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ )}
+ </DialogContent>
+ </Dialog>
+
+ {/* Delete Confirmation Dialog */}
+ <Dialog open={!!deleteUser} onOpenChange={(open) => !open && setDeleteUser(null)}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>{t('admin.users.confirmDeleteTitle')}</DialogTitle>
+ <DialogDescription>
+ {t('admin.users.confirmDeleteDesc', { email: deleteUser?.email })}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter className="mt-2">
+ <Button variant="outline" onClick={() => setDeleteUser(null)} className="rounded-lg">
+ {t('common.cancel')}
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={deleteMutation.isPending}
+ onClick={() => deleteUser && deleteMutation.mutate(deleteUser.id)}
+ className="rounded-lg"
+ >
+ {deleteMutation.isPending ? t('common.loading') : t('common.delete')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsx
index d012b1b4..7d6910cb 100644
--- a/frontend/src/pages/login.tsx
+++ b/frontend/src/pages/login.tsx
@@ -2,11 +2,11 @@ import { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuth } from '@/contexts/auth-context'
-import { setup } from '@/lib/api'
+import { setup, admin as adminApi } from '@/lib/api'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
-import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
+import { Card, CardContent, CardFooter } from '@/components/ui/card'
import { ShellLogo } from '@/components/shell-logo'
export default function LoginPage() {
@@ -17,6 +17,7 @@ export default function LoginPage() {
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [isLoading, setIsLoading] = useState(false)
+ const [registrationEnabled, setRegistrationEnabled] = useState(true)
useEffect(() => {
if (token) {
@@ -28,6 +29,9 @@ export default function LoginPage() {
navigate('/setup', { replace: true })
}
}).catch(() => {})
+ adminApi.registrationStatus().then(({ enabled }) => {
+ setRegistrationEnabled(enabled)
+ }).catch(() => {})
}, [navigate, token])
const handleSubmit = async (e: React.FormEvent) => {
@@ -45,59 +49,56 @@ export default function LoginPage() {
}
return (
- <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-primary/5 px-4">
- <div className="flex items-center gap-3 mb-10">
- <div className="w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center">
- <ShellLogo size={24} className="text-primary" />
- </div>
- <span className="text-2xl font-bold tracking-tight text-foreground">{t('app.name')}</span>
- </div>
- <Card className="w-full max-w-[400px] shadow-lg border-border/60">
+ <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={handleSubmit}>
- <CardHeader className="text-center pb-2 pt-8 px-8">
- <CardTitle className="text-2xl font-bold tracking-tight">{t('auth.login')}</CardTitle>
- <CardDescription className="text-[13px] mt-1">{t('auth.loginDescription')}</CardDescription>
- </CardHeader>
- <CardContent className="space-y-5 px-8 pt-4">
+ <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.login')}</h1>
+ <p className="text-sm text-muted-foreground mt-1">{t('auth.loginDescription')}</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="email" className="text-[13px] font-medium">{t('auth.email')}</Label>
+ <Label htmlFor="email" className="text-sm">{t('auth.email')}</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
- className="h-11 rounded-lg text-sm"
placeholder="[email protected]"
required
/>
</div>
<div className="space-y-1.5">
- <Label htmlFor="password" className="text-[13px] font-medium">{t('auth.password')}</Label>
+ <Label htmlFor="password" className="text-sm">{t('auth.password')}</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
- className="h-11 rounded-lg text-sm"
required
/>
</div>
</CardContent>
<CardFooter className="flex flex-col gap-4 px-8 pb-8 pt-2">
- <Button type="submit" className="w-full h-11 rounded-lg text-sm font-semibold" disabled={isLoading}>
+ <Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? t('common.loading') : t('auth.login')}
</Button>
- <p className="text-[13px] text-muted-foreground">
- {t('auth.noAccount')}{' '}
- <Link to="/register" className="text-primary font-medium hover:underline">
- {t('auth.register')}
- </Link>
- </p>
+ {registrationEnabled && (
+ <p className="text-sm text-muted-foreground">
+ {t('auth.noAccount')}{' '}
+ <Link to="/register" className="text-primary font-medium hover:underline">
+ {t('auth.register')}
+ </Link>
+ </p>
+ )}
</CardFooter>
</form>
</Card>
diff --git a/frontend/src/pages/register.tsx b/frontend/src/pages/register.tsx
index a24f2edc..4b0e9275 100644
--- a/frontend/src/pages/register.tsx
+++ b/frontend/src/pages/register.tsx
@@ -1,23 +1,43 @@
-import { useState } from 'react'
+import { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuth } from '@/contexts/auth-context'
+import { admin as adminApi } from '@/lib/api'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
-import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
+import { Card, CardContent, CardFooter } from '@/components/ui/card'
import { ShellLogo } from '@/components/shell-logo'
+import { cn } from '@/lib/utils'
+
+const currencies = [
+ { code: 'USD', flag: '\u{1F1FA}\u{1F1F8}', symbol: '$' },
+ { code: 'EUR', flag: '\u{1F1EA}\u{1F1FA}', symbol: '\u20AC' },
+ { code: 'GBP', flag: '\u{1F1EC}\u{1F1E7}', symbol: '\u00A3' },
+ { code: 'BRL', flag: '\u{1F1E7}\u{1F1F7}', symbol: 'R$' },
+ { code: 'CAD', flag: '\u{1F1E8}\u{1F1E6}', symbol: 'C$' },
+ { code: 'AUD', flag: '\u{1F1E6}\u{1F1FA}', symbol: 'A$' },
+ { code: 'CHF', flag: '\u{1F1E8}\u{1F1ED}', symbol: 'Fr' },
+ { code: 'ARS', flag: '\u{1F1E6}\u{1F1F7}', symbol: '$' },
+] as const
export default function RegisterPage() {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
const { register } = useAuth()
const navigate = useNavigate()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
+ const [currency, setCurrency] = useState('USD')
const [error, setError] = useState('')
const [isLoading, setIsLoading] = useState(false)
+ useEffect(() => {
+ adminApi.registrationStatus().then(({ enabled }) => {
+ if (!enabled) navigate('/login', { replace: true })
+ }).catch(() => {})
+ }, [navigate])
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
@@ -34,7 +54,11 @@ export default function RegisterPage() {
setIsLoading(true)
try {
- await register(email, password)
+ const lang = i18n.language?.startsWith('pt') ? 'pt-BR' : 'en'
+ await register(email, password, {
+ currency_display: currency,
+ language: lang,
+ })
navigate('/')
} catch {
setError(t('auth.registrationError'))
@@ -44,37 +68,35 @@ export default function RegisterPage() {
}
return (
- <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-primary/5">
- <div className="flex items-center gap-2.5 mb-8">
- <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
- <ShellLogo size={20} className="text-primary" />
- </div>
- <span className="text-xl font-bold tracking-tight text-foreground">{t('app.name')}</span>
- </div>
- <Card className="w-full max-w-sm">
- <CardHeader className="text-center">
- <CardTitle className="text-xl font-semibold">{t('auth.register')}</CardTitle>
- <CardDescription>{t('auth.register')}</CardDescription>
- </CardHeader>
+ <div className="flex flex-col items-center justify-center min-h-screen bg-background px-4">
+ <Card className="w-full max-w-[400px] shadow-sm">
<form onSubmit={handleSubmit}>
- <CardContent className="space-y-4">
+ <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.register')}</h1>
+ <p className="text-sm text-muted-foreground mt-1">{t('auth.registerDescription')}</p>
+ </div>
+ <CardContent className="space-y-4 px-8 pt-4">
{error && (
- <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
+ <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-lg">
{error}
</div>
)}
- <div className="space-y-2">
- <Label htmlFor="email">{t('auth.email')}</Label>
+ <div className="space-y-1.5">
+ <Label htmlFor="email" className="text-sm">{t('auth.email')}</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
+ placeholder="[email protected]"
required
/>
</div>
- <div className="space-y-2">
- <Label htmlFor="password">{t('auth.password')}</Label>
+ <div className="space-y-1.5">
+ <Label htmlFor="password" className="text-sm">{t('auth.password')}</Label>
<Input
id="password"
type="password"
@@ -84,8 +106,8 @@ export default function RegisterPage() {
minLength={8}
/>
</div>
- <div className="space-y-2">
- <Label htmlFor="confirmPassword">{t('auth.confirmPassword')}</Label>
+ <div className="space-y-1.5">
+ <Label htmlFor="confirmPassword" className="text-sm">{t('auth.confirmPassword')}</Label>
<Input
id="confirmPassword"
type="password"
@@ -94,14 +116,36 @@ export default function RegisterPage() {
required
/>
</div>
+ <div className="space-y-2 pt-1">
+ <Label className="text-sm">{t('auth.currency')}</Label>
+ <div className="grid grid-cols-4 gap-2">
+ {currencies.map(({ code, flag, symbol }) => (
+ <button
+ key={code}
+ type="button"
+ onClick={() => setCurrency(code)}
+ className={cn(
+ 'flex flex-col items-center gap-1 py-2.5 rounded-lg border transition-all',
+ currency === code
+ ? 'border-primary bg-primary/10 text-primary ring-1 ring-primary/30'
+ : 'border-border text-muted-foreground hover:border-foreground/20 hover:text-foreground'
+ )}
+ >
+ <span className="text-lg leading-none">{flag}</span>
+ <span className="text-[11px] font-bold">{code}</span>
+ <span className="text-[10px] opacity-60">{symbol}</span>
+ </button>
+ ))}
+ </div>
+ </div>
</CardContent>
- <CardFooter className="flex flex-col gap-4">
+ <CardFooter className="flex flex-col gap-4 px-8 pb-8 pt-2">
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? t('common.loading') : t('auth.register')}
</Button>
<p className="text-sm text-muted-foreground">
{t('auth.hasAccount')}{' '}
- <Link to="/login" className="text-primary hover:underline">
+ <Link to="/login" className="text-primary font-medium hover:underline">
{t('auth.login')}
</Link>
</p>
diff --git a/frontend/src/pages/setup.tsx b/frontend/src/pages/setup.tsx
index 14af447e..e33602c2 100644
--- a/frontend/src/pages/setup.tsx
+++ b/frontend/src/pages/setup.tsx
@@ -7,7 +7,7 @@ import { useAuth } from '@/contexts/auth-context'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
-import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
+import { Card, CardContent, CardFooter } from '@/components/ui/card'
import { cn } from '@/lib/utils'
import { Sun, Moon, Globe } from 'lucide-react'
import { ShellLogo } from '@/components/shell-logo'
@@ -74,74 +74,71 @@ export default function SetupPage() {
}
return (
- <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-primary/5 px-4">
- <div className="flex items-center gap-3 mb-10">
- <div className="w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center">
- <ShellLogo size={24} className="text-primary" />
- </div>
- <span className="text-2xl font-bold tracking-tight text-foreground">{t('app.name')}</span>
- </div>
- <Card className="w-full max-w-[400px] shadow-lg border-border/60">
+ <div className="flex flex-col items-center justify-center min-h-screen bg-background px-4">
+ <Card className="w-full max-w-[400px] shadow-sm">
<form onSubmit={handleSubmit}>
- <CardHeader className="text-center pb-2 pt-8 px-8">
- <CardTitle className="text-2xl font-bold tracking-tight">{t('setup.title')}</CardTitle>
- <CardDescription className="text-[13px] mt-1">{t('setup.description')}</CardDescription>
- </CardHeader>
- <CardContent className="space-y-5 px-8 pt-4">
+ <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('setup.title')}</h1>
+ <p className="text-sm text-muted-foreground mt-1">{t('setup.description')}</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="name" className="text-[13px] font-medium">{t('setup.name')}</Label>
+ <Label htmlFor="name" className="text-sm">{t('setup.name')}</Label>
<Input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
- className="h-11 rounded-lg text-sm"
+
placeholder={t('setup.namePlaceholder')}
/>
</div>
<div className="space-y-1.5">
- <Label htmlFor="email" className="text-[13px] font-medium">{t('auth.email')}</Label>
+ <Label htmlFor="email" className="text-sm">{t('auth.email')}</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
- className="h-11 rounded-lg text-sm"
+
placeholder="[email protected]"
required
/>
</div>
<div className="space-y-1.5">
- <Label htmlFor="password" className="text-[13px] font-medium">{t('auth.password')}</Label>
+ <Label htmlFor="password" className="text-sm">{t('auth.password')}</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
- className="h-11 rounded-lg text-sm"
+
required
minLength={8}
/>
</div>
<div className="space-y-1.5">
- <Label htmlFor="confirmPassword" className="text-[13px] font-medium">{t('setup.confirmPassword')}</Label>
+ <Label htmlFor="confirmPassword" className="text-sm">{t('setup.confirmPassword')}</Label>
<Input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
- className="h-11 rounded-lg text-sm"
+
required
minLength={8}
/>
</div>
<div className="space-y-2 pt-1">
- <Label className="text-[13px] font-medium">{t('setup.currency')}</Label>
+ <Label className="text-sm">{t('setup.currency')}</Label>
<div className="grid grid-cols-4 gap-2">
{([
{ code: 'USD', flag: '\u{1F1FA}\u{1F1F8}', symbol: '$' },
@@ -173,7 +170,7 @@ export default function SetupPage() {
</div>
<div className="flex items-center justify-between gap-4 pt-1">
<div className="space-y-1.5">
- <Label className="text-[13px] font-medium flex items-center gap-1.5">
+ <Label className="text-sm flex items-center gap-1.5">
<Globe size={14} />
{t('setup.language')}
</Label>
@@ -205,7 +202,7 @@ export default function SetupPage() {
</div>
</div>
<div className="space-y-1.5">
- <Label className="text-[13px] font-medium">{t('setup.theme')}</Label>
+ <Label className="text-sm">{t('setup.theme')}</Label>
<div className="flex items-center gap-1">
<button
type="button"
@@ -236,7 +233,7 @@ export default function SetupPage() {
</div>
</CardContent>
<CardFooter className="px-8 pb-8 pt-2">
- <Button type="submit" className="w-full h-11 rounded-lg text-sm font-semibold" disabled={isLoading}>
+ <Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? t('setup.creating') : t('setup.createAdmin')}
</Button>
</CardFooter>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 363badc2..67bb6b71 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -1,9 +1,31 @@
export interface User {
id: string
email: string
+ is_active: boolean
+ is_superuser: boolean
+ is_verified: boolean
preferences: UserPreferences
}
+export interface AdminUser {
+ id: string
+ email: string
+ is_active: boolean
+ is_superuser: boolean
+ is_verified: boolean
+ preferences: UserPreferences | null
+}
+
+export interface AdminUserList {
+ items: AdminUser[]
+ total: number
+}
+
+export interface AppSetting {
+ key: string
+ value: string
+}
+
export interface UserPreferences {
language?: string
date_format?: string