Phase 1: Foundation — backend auth, frontend shell, Docker setup
Backend (FastAPI): - App factory with async SQLAlchemy 2.0 + PostgreSQL - Alembic migration for users and sessions tables - JWT auth (access + refresh tokens, bcrypt passwords) - Auth endpoints: register, login, refresh, logout, me - Admin seed script, role-based access deps Frontend (React + TypeScript): - Vite + Tailwind CSS + shadcn/ui theme (health-oriented palette) - i18n with English and Russian translations - Zustand auth/UI stores with localStorage persistence - Axios client with automatic token refresh on 401 - Login/register pages, protected routing - App layout: collapsible sidebar, header with theme/language toggles - Dashboard with placeholder stats Infrastructure: - Docker Compose (postgres, backend, frontend, nginx) - Nginx reverse proxy with WebSocket support - Dev override with hot reload Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
20
.env.example
Normal file
20
.env.example
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# PostgreSQL
|
||||||
|
POSTGRES_USER=ai_assistant
|
||||||
|
POSTGRES_PASSWORD=changeme_db_password
|
||||||
|
POSTGRES_DB=ai_assistant
|
||||||
|
|
||||||
|
# Backend
|
||||||
|
DATABASE_URL=postgresql+asyncpg://ai_assistant:changeme_db_password@postgres:5432/ai_assistant
|
||||||
|
SECRET_KEY=changeme_secret_key_at_least_32_chars_long
|
||||||
|
BACKEND_CORS_ORIGINS=["http://localhost","http://localhost:3000"]
|
||||||
|
ENVIRONMENT=development
|
||||||
|
|
||||||
|
# Auth
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES=15
|
||||||
|
REFRESH_TOKEN_EXPIRE_DAYS=30
|
||||||
|
REFRESH_TOKEN_EXPIRE_HOURS=24
|
||||||
|
|
||||||
|
# Admin seed
|
||||||
|
FIRST_ADMIN_EMAIL=admin@example.com
|
||||||
|
FIRST_ADMIN_USERNAME=admin
|
||||||
|
FIRST_ADMIN_PASSWORD=changeme_admin_password
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -33,6 +33,7 @@ data/
|
|||||||
|
|
||||||
# Generated files
|
# Generated files
|
||||||
*.log
|
*.log
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
# Test / coverage
|
# Test / coverage
|
||||||
.coverage
|
.coverage
|
||||||
|
|||||||
@@ -202,8 +202,8 @@ Daily scheduled job (APScheduler, 8 AM) reviews each user's memory + recent docs
|
|||||||
## Implementation Phases
|
## Implementation Phases
|
||||||
|
|
||||||
### Phase 1: Foundation
|
### Phase 1: Foundation
|
||||||
- **Status**: NOT STARTED
|
- **Status**: IN PROGRESS
|
||||||
- [ ] Subplan created (`plans/phase-1-foundation.md`)
|
- [x] Subplan created (`plans/phase-1-foundation.md`)
|
||||||
- [ ] Phase completed
|
- [ ] Phase completed
|
||||||
- Summary: Monorepo setup, Docker Compose, FastAPI + Alembic, auth (JWT), frontend shell (Vite + React + shadcn/ui + i18n), seed admin script
|
- Summary: Monorepo setup, Docker Compose, FastAPI + Alembic, auth (JWT), frontend shell (Vite + React + shadcn/ui + i18n), seed admin script
|
||||||
|
|
||||||
|
|||||||
14
backend/Dockerfile
Normal file
14
backend/Dockerfile
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
gcc libpq-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY pyproject.toml .
|
||||||
|
RUN pip install --no-cache-dir .
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
|
||||||
36
backend/alembic.ini
Normal file
36
backend/alembic.ini
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = alembic
|
||||||
|
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
46
backend/alembic/env.py
Normal file
46
backend/alembic/env.py
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import asyncio
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.database import Base
|
||||||
|
from app.models import User, Session # noqa: F401 — ensure models are registered
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
url = settings.DATABASE_URL
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def do_run_migrations(connection):
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
async def run_migrations_online() -> None:
|
||||||
|
connectable = create_async_engine(settings.DATABASE_URL)
|
||||||
|
async with connectable.connect() as connection:
|
||||||
|
await connection.run_sync(do_run_migrations)
|
||||||
|
await connectable.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
asyncio.run(run_migrations_online())
|
||||||
26
backend/alembic/script.py.mako
Normal file
26
backend/alembic/script.py.mako
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
53
backend/alembic/versions/001_create_users_and_sessions.py
Normal file
53
backend/alembic/versions/001_create_users_and_sessions.py
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
"""Create users and sessions tables
|
||||||
|
|
||||||
|
Revision ID: 001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-03-19
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
|
||||||
|
revision: str = "001"
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"users",
|
||||||
|
sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
|
||||||
|
sa.Column("email", sa.String(255), unique=True, nullable=False, index=True),
|
||||||
|
sa.Column("username", sa.String(100), unique=True, nullable=False, index=True),
|
||||||
|
sa.Column("hashed_password", sa.String(255), nullable=False),
|
||||||
|
sa.Column("full_name", sa.String(255), nullable=True),
|
||||||
|
sa.Column("role", sa.String(20), nullable=False, server_default="user"),
|
||||||
|
sa.Column("is_active", sa.Boolean, nullable=False, server_default=sa.text("true")),
|
||||||
|
sa.Column("max_chats", sa.Integer, nullable=False, server_default=sa.text("10")),
|
||||||
|
sa.Column("oauth_provider", sa.String(50), nullable=True),
|
||||||
|
sa.Column("oauth_provider_id", sa.String(255), nullable=True),
|
||||||
|
sa.Column("telegram_chat_id", sa.BigInteger, nullable=True),
|
||||||
|
sa.Column("avatar_url", sa.String(500), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"sessions",
|
||||||
|
sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
|
||||||
|
sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True),
|
||||||
|
sa.Column("refresh_token_hash", sa.String(255), nullable=False, index=True),
|
||||||
|
sa.Column("device_info", sa.String(500), nullable=True),
|
||||||
|
sa.Column("ip_address", sa.String(45), nullable=True),
|
||||||
|
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("sessions")
|
||||||
|
op.drop_table("users")
|
||||||
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
67
backend/app/api/deps.py
Normal file
67
backend/app/api/deps.py
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import uuid
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordBearer
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.core.security import decode_access_token
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login", auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(
|
||||||
|
token: Annotated[str | None, Depends(oauth2_scheme)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
) -> User:
|
||||||
|
if not token:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Not authenticated",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
payload = decode_access_token(token)
|
||||||
|
user_id = payload.get("sub")
|
||||||
|
|
||||||
|
if not user_id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid token",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
uid = uuid.UUID(user_id)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid token",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await db.execute(select(User).where(User.id == uid))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user or not user.is_active:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="User not found or inactive",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
async def require_admin(
|
||||||
|
user: Annotated[User, Depends(get_current_user)],
|
||||||
|
) -> User:
|
||||||
|
if user.role != "admin":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Admin access required",
|
||||||
|
)
|
||||||
|
return user
|
||||||
0
backend/app/api/v1/__init__.py
Normal file
0
backend/app/api/v1/__init__.py
Normal file
70
backend/app/api/v1/auth.py
Normal file
70
backend/app/api/v1/auth.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Request, status
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.api.deps import get_current_user
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.auth import (
|
||||||
|
AuthResponse,
|
||||||
|
LoginRequest,
|
||||||
|
RefreshRequest,
|
||||||
|
TokenResponse,
|
||||||
|
UserResponse,
|
||||||
|
RegisterRequest,
|
||||||
|
)
|
||||||
|
from app.services import auth_service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register", response_model=AuthResponse, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def register(
|
||||||
|
data: RegisterRequest,
|
||||||
|
request: Request,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
):
|
||||||
|
return await auth_service.register_user(
|
||||||
|
db,
|
||||||
|
data,
|
||||||
|
ip_address=request.client.host if request.client else None,
|
||||||
|
device_info=request.headers.get("user-agent"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login", response_model=AuthResponse)
|
||||||
|
async def login(
|
||||||
|
data: LoginRequest,
|
||||||
|
request: Request,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
):
|
||||||
|
return await auth_service.login_user(
|
||||||
|
db,
|
||||||
|
email=data.email,
|
||||||
|
password=data.password,
|
||||||
|
remember_me=data.remember_me,
|
||||||
|
ip_address=request.client.host if request.client else None,
|
||||||
|
device_info=request.headers.get("user-agent"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/refresh", response_model=TokenResponse)
|
||||||
|
async def refresh(
|
||||||
|
data: RefreshRequest,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
):
|
||||||
|
return await auth_service.refresh_tokens(db, data.refresh_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def logout(
|
||||||
|
data: RefreshRequest,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
):
|
||||||
|
await auth_service.logout_user(db, data.refresh_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserResponse)
|
||||||
|
async def me(user: Annotated[User, Depends(get_current_user)]):
|
||||||
|
return UserResponse.model_validate(user)
|
||||||
12
backend/app/api/v1/router.py
Normal file
12
backend/app/api/v1/router.py
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.v1.auth import router as auth_router
|
||||||
|
|
||||||
|
api_v1_router = APIRouter(prefix="/api/v1")
|
||||||
|
|
||||||
|
api_v1_router.include_router(auth_router)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1_router.get("/health")
|
||||||
|
async def health():
|
||||||
|
return {"status": "ok"}
|
||||||
22
backend/app/config.py
Normal file
22
backend/app/config.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
DATABASE_URL: str = "postgresql+asyncpg://ai_assistant:changeme@postgres:5432/ai_assistant"
|
||||||
|
SECRET_KEY: str = "changeme_secret_key_at_least_32_chars_long"
|
||||||
|
ENVIRONMENT: str = "development"
|
||||||
|
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
|
||||||
|
REFRESH_TOKEN_EXPIRE_DAYS: int = 30
|
||||||
|
REFRESH_TOKEN_EXPIRE_HOURS: int = 24
|
||||||
|
|
||||||
|
BACKEND_CORS_ORIGINS: list[str] = ["http://localhost", "http://localhost:3000"]
|
||||||
|
|
||||||
|
FIRST_ADMIN_EMAIL: str = "admin@example.com"
|
||||||
|
FIRST_ADMIN_USERNAME: str = "admin"
|
||||||
|
FIRST_ADMIN_PASSWORD: str = "changeme_admin_password"
|
||||||
|
|
||||||
|
model_config = {"env_file": ".env", "extra": "ignore"}
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings()
|
||||||
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
49
backend/app/core/security.py
Normal file
49
backend/app/core/security.py
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
ALGORITHM = "HS256"
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return pwd_context.hash(password)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
|
return pwd_context.verify(plain_password, hashed_password)
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(user_id: uuid.UUID, role: str) -> str:
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
expire = now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
payload = {
|
||||||
|
"sub": str(user_id),
|
||||||
|
"role": role,
|
||||||
|
"exp": expire,
|
||||||
|
"iat": now,
|
||||||
|
"jti": str(uuid.uuid4()),
|
||||||
|
}
|
||||||
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm=ALGORITHM)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_access_token(token: str) -> dict:
|
||||||
|
try:
|
||||||
|
return jwt.decode(token, settings.SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
|
except JWTError:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def generate_refresh_token() -> str:
|
||||||
|
return secrets.token_hex(64)
|
||||||
|
|
||||||
|
|
||||||
|
def hash_refresh_token(token: str) -> str:
|
||||||
|
return hashlib.sha256(token.encode()).hexdigest()
|
||||||
32
backend/app/database.py
Normal file
32
backend/app/database.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import uuid
|
||||||
|
from collections.abc import AsyncGenerator
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, func
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
engine = create_async_engine(settings.DATABASE_URL, echo=settings.ENVIRONMENT == "development")
|
||||||
|
async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||||
|
async with async_session_factory() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
await session.commit()
|
||||||
|
except Exception:
|
||||||
|
await session.rollback()
|
||||||
|
raise
|
||||||
40
backend/app/main.py
Normal file
40
backend/app/main.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
from alembic import command
|
||||||
|
from alembic.config import Config
|
||||||
|
|
||||||
|
alembic_cfg = Config("alembic.ini")
|
||||||
|
command.upgrade(alembic_cfg, "head")
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
app = FastAPI(
|
||||||
|
title="AI Assistant API",
|
||||||
|
version="0.1.0",
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.BACKEND_CORS_ORIGINS,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.api.v1.router import api_v1_router
|
||||||
|
app.include_router(api_v1_router)
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
4
backend/app/models/__init__.py
Normal file
4
backend/app/models/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
from app.models.user import User
|
||||||
|
from app.models.session import Session
|
||||||
|
|
||||||
|
__all__ = ["User", "Session"]
|
||||||
22
backend/app/models/session.py
Normal file
22
backend/app/models/session.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, ForeignKey, String
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Session(Base):
|
||||||
|
__tablename__ = "sessions"
|
||||||
|
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
refresh_token_hash: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||||
|
device_info: Mapped[str | None] = mapped_column(String(500), nullable=True)
|
||||||
|
ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True)
|
||||||
|
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
|
||||||
|
user: Mapped["User"] = relationship(back_populates="sessions") # noqa: F821
|
||||||
27
backend/app/models/user.py
Normal file
27
backend/app/models/user.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, DateTime, Integer, String, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
|
||||||
|
username: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False)
|
||||||
|
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
full_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||||
|
role: Mapped[str] = mapped_column(String(20), nullable=False, default="user")
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||||
|
max_chats: Mapped[int] = mapped_column(Integer, nullable=False, default=10)
|
||||||
|
oauth_provider: Mapped[str | None] = mapped_column(String(50), nullable=True)
|
||||||
|
oauth_provider_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||||
|
telegram_chat_id: Mapped[int | None] = mapped_column(nullable=True)
|
||||||
|
avatar_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
sessions: Mapped[list["Session"]] = relationship(back_populates="user", cascade="all, delete-orphan") # noqa: F821
|
||||||
0
backend/app/schemas/__init__.py
Normal file
0
backend/app/schemas/__init__.py
Normal file
46
backend/app/schemas/auth.py
Normal file
46
backend/app/schemas/auth.py
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
username: str = Field(min_length=3, max_length=50, pattern=r"^[a-zA-Z0-9_-]+$")
|
||||||
|
password: str = Field(min_length=8, max_length=128)
|
||||||
|
full_name: str | None = Field(default=None, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
password: str
|
||||||
|
remember_me: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshRequest(BaseModel):
|
||||||
|
refresh_token: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
email: str
|
||||||
|
username: str
|
||||||
|
full_name: str | None
|
||||||
|
role: str
|
||||||
|
is_active: bool
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
class AuthResponse(BaseModel):
|
||||||
|
user: UserResponse
|
||||||
|
access_token: str
|
||||||
|
refresh_token: str
|
||||||
|
token_type: str = "bearer"
|
||||||
|
|
||||||
|
|
||||||
|
class TokenResponse(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
refresh_token: str
|
||||||
|
token_type: str = "bearer"
|
||||||
5
backend/app/schemas/common.py
Normal file
5
backend/app/schemas/common.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class MessageResponse(BaseModel):
|
||||||
|
message: str
|
||||||
0
backend/app/services/__init__.py
Normal file
0
backend/app/services/__init__.py
Normal file
162
backend/app/services/auth_service.py
Normal file
162
backend/app/services/auth_service.py
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from fastapi import HTTPException, status
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.core.security import (
|
||||||
|
create_access_token,
|
||||||
|
generate_refresh_token,
|
||||||
|
hash_password,
|
||||||
|
hash_refresh_token,
|
||||||
|
verify_password,
|
||||||
|
)
|
||||||
|
from app.models.session import Session
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.auth import AuthResponse, RegisterRequest, TokenResponse, UserResponse
|
||||||
|
|
||||||
|
|
||||||
|
async def _create_session(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
remember_me: bool,
|
||||||
|
ip_address: str | None = None,
|
||||||
|
device_info: str | None = None,
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
access_token = create_access_token(user.id, user.role)
|
||||||
|
refresh_token = generate_refresh_token()
|
||||||
|
|
||||||
|
if remember_me:
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
||||||
|
else:
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(hours=settings.REFRESH_TOKEN_EXPIRE_HOURS)
|
||||||
|
|
||||||
|
session = Session(
|
||||||
|
user_id=user.id,
|
||||||
|
refresh_token_hash=hash_refresh_token(refresh_token),
|
||||||
|
device_info=device_info,
|
||||||
|
ip_address=ip_address,
|
||||||
|
expires_at=expires_at,
|
||||||
|
)
|
||||||
|
db.add(session)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
return access_token, refresh_token
|
||||||
|
|
||||||
|
|
||||||
|
async def register_user(
|
||||||
|
db: AsyncSession,
|
||||||
|
data: RegisterRequest,
|
||||||
|
ip_address: str | None = None,
|
||||||
|
device_info: str | None = None,
|
||||||
|
) -> AuthResponse:
|
||||||
|
existing = await db.execute(
|
||||||
|
select(User).where((User.email == data.email) | (User.username == data.username))
|
||||||
|
)
|
||||||
|
if existing.scalar_one_or_none():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="User with this email or username already exists",
|
||||||
|
)
|
||||||
|
|
||||||
|
user = User(
|
||||||
|
email=data.email,
|
||||||
|
username=data.username,
|
||||||
|
hashed_password=hash_password(data.password),
|
||||||
|
full_name=data.full_name,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
access_token, refresh_token = await _create_session(db, user, remember_me=False, ip_address=ip_address, device_info=device_info)
|
||||||
|
|
||||||
|
return AuthResponse(
|
||||||
|
user=UserResponse.model_validate(user),
|
||||||
|
access_token=access_token,
|
||||||
|
refresh_token=refresh_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def login_user(
|
||||||
|
db: AsyncSession,
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
remember_me: bool = False,
|
||||||
|
ip_address: str | None = None,
|
||||||
|
device_info: str | None = None,
|
||||||
|
) -> AuthResponse:
|
||||||
|
result = await db.execute(select(User).where(User.email == email))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user or not verify_password(password, user.hashed_password):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid email or password",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not user.is_active:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Account is deactivated",
|
||||||
|
)
|
||||||
|
|
||||||
|
access_token, refresh_token = await _create_session(db, user, remember_me, ip_address, device_info)
|
||||||
|
|
||||||
|
return AuthResponse(
|
||||||
|
user=UserResponse.model_validate(user),
|
||||||
|
access_token=access_token,
|
||||||
|
refresh_token=refresh_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def refresh_tokens(db: AsyncSession, refresh_token: str) -> TokenResponse:
|
||||||
|
token_hash = hash_refresh_token(refresh_token)
|
||||||
|
result = await db.execute(
|
||||||
|
select(Session).where(Session.refresh_token_hash == token_hash)
|
||||||
|
)
|
||||||
|
session = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not session:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid refresh token",
|
||||||
|
)
|
||||||
|
|
||||||
|
if session.expires_at < datetime.now(timezone.utc):
|
||||||
|
await db.delete(session)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Refresh token expired",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await db.execute(select(User).where(User.id == session.user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user or not user.is_active:
|
||||||
|
await db.delete(session)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="User not found or inactive",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Rotate refresh token
|
||||||
|
new_refresh_token = generate_refresh_token()
|
||||||
|
session.refresh_token_hash = hash_refresh_token(new_refresh_token)
|
||||||
|
new_access_token = create_access_token(user.id, user.role)
|
||||||
|
|
||||||
|
return TokenResponse(
|
||||||
|
access_token=new_access_token,
|
||||||
|
refresh_token=new_refresh_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def logout_user(db: AsyncSession, refresh_token: str) -> None:
|
||||||
|
token_hash = hash_refresh_token(refresh_token)
|
||||||
|
result = await db.execute(
|
||||||
|
select(Session).where(Session.refresh_token_hash == token_hash)
|
||||||
|
)
|
||||||
|
session = result.scalar_one_or_none()
|
||||||
|
if session:
|
||||||
|
await db.delete(session)
|
||||||
33
backend/pyproject.toml
Normal file
33
backend/pyproject.toml
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
[project]
|
||||||
|
name = "ai-assistant-backend"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Personal AI Assistant - Backend"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115.0",
|
||||||
|
"uvicorn[standard]>=0.30.0",
|
||||||
|
"sqlalchemy[asyncio]>=2.0.30",
|
||||||
|
"asyncpg>=0.30.0",
|
||||||
|
"alembic>=1.13.0",
|
||||||
|
"pydantic[email]>=2.9.0",
|
||||||
|
"pydantic-settings>=2.5.0",
|
||||||
|
"passlib[bcrypt]>=1.7.4",
|
||||||
|
"python-jose[cryptography]>=3.3.0",
|
||||||
|
"python-multipart>=0.0.9",
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"pytest>=8.0.0",
|
||||||
|
"pytest-asyncio>=0.24.0",
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=69.0"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
asyncio_mode = "auto"
|
||||||
|
testpaths = ["tests"]
|
||||||
0
backend/scripts/__init__.py
Normal file
0
backend/scripts/__init__.py
Normal file
35
backend/scripts/seed_admin.py
Normal file
35
backend/scripts/seed_admin.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
"""Create the initial admin user if it doesn't already exist."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.core.security import hash_password
|
||||||
|
from app.database import async_session_factory
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
|
|
||||||
|
async def seed_admin() -> None:
|
||||||
|
async with async_session_factory() as db:
|
||||||
|
result = await db.execute(select(User).where(User.email == settings.FIRST_ADMIN_EMAIL))
|
||||||
|
existing = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
print(f"Admin user already exists: {existing.email}")
|
||||||
|
return
|
||||||
|
|
||||||
|
admin = User(
|
||||||
|
email=settings.FIRST_ADMIN_EMAIL,
|
||||||
|
username=settings.FIRST_ADMIN_USERNAME,
|
||||||
|
hashed_password=hash_password(settings.FIRST_ADMIN_PASSWORD),
|
||||||
|
full_name="Administrator",
|
||||||
|
role="admin",
|
||||||
|
)
|
||||||
|
db.add(admin)
|
||||||
|
await db.commit()
|
||||||
|
print(f"Admin user created: {admin.email}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(seed_admin())
|
||||||
0
backend/tests/__init__.py
Normal file
0
backend/tests/__init__.py
Normal file
61
backend/tests/conftest.py
Normal file
61
backend/tests/conftest.py
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
from collections.abc import AsyncGenerator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
|
||||||
|
from app.database import Base, get_db
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
# Use a unique in-memory-like approach: create a separate test DB schema
|
||||||
|
TEST_DATABASE_URL = "postgresql+asyncpg://ai_assistant:changeme@localhost:5432/ai_assistant_test"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def event_loop():
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
yield loop
|
||||||
|
loop.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
async def test_engine():
|
||||||
|
engine = create_async_engine(TEST_DATABASE_URL)
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.run_sync(Base.metadata.drop_all)
|
||||||
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
yield engine
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.run_sync(Base.metadata.drop_all)
|
||||||
|
await engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def db_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
|
||||||
|
session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
async with session_factory() as session:
|
||||||
|
yield session
|
||||||
|
await session.rollback()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def client(test_engine) -> AsyncGenerator[AsyncClient, None]:
|
||||||
|
session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
|
||||||
|
async def override_get_db():
|
||||||
|
async with session_factory() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
await session.commit()
|
||||||
|
except Exception:
|
||||||
|
await session.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
app.dependency_overrides[get_db] = override_get_db
|
||||||
|
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||||
|
yield ac
|
||||||
135
backend/tests/test_auth.py
Normal file
135
backend/tests/test_auth.py
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def registered_user(client: AsyncClient):
|
||||||
|
resp = await client.post("/api/v1/auth/register", json={
|
||||||
|
"email": "test@example.com",
|
||||||
|
"username": "testuser",
|
||||||
|
"password": "testpass123",
|
||||||
|
"full_name": "Test User",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 201
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_health(client: AsyncClient):
|
||||||
|
resp = await client.get("/api/v1/health")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_register_success(client: AsyncClient):
|
||||||
|
resp = await client.post("/api/v1/auth/register", json={
|
||||||
|
"email": "new@example.com",
|
||||||
|
"username": "newuser",
|
||||||
|
"password": "password123",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 201
|
||||||
|
data = resp.json()
|
||||||
|
assert data["user"]["email"] == "new@example.com"
|
||||||
|
assert data["user"]["username"] == "newuser"
|
||||||
|
assert data["user"]["role"] == "user"
|
||||||
|
assert "access_token" in data
|
||||||
|
assert "refresh_token" in data
|
||||||
|
|
||||||
|
|
||||||
|
async def test_register_duplicate_email(client: AsyncClient, registered_user):
|
||||||
|
resp = await client.post("/api/v1/auth/register", json={
|
||||||
|
"email": "test@example.com",
|
||||||
|
"username": "different",
|
||||||
|
"password": "password123",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
async def test_register_short_password(client: AsyncClient):
|
||||||
|
resp = await client.post("/api/v1/auth/register", json={
|
||||||
|
"email": "short@example.com",
|
||||||
|
"username": "shortpw",
|
||||||
|
"password": "short",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_success(client: AsyncClient, registered_user):
|
||||||
|
resp = await client.post("/api/v1/auth/login", json={
|
||||||
|
"email": "test@example.com",
|
||||||
|
"password": "testpass123",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["user"]["email"] == "test@example.com"
|
||||||
|
assert "access_token" in data
|
||||||
|
assert "refresh_token" in data
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_invalid_credentials(client: AsyncClient, registered_user):
|
||||||
|
resp = await client.post("/api/v1/auth/login", json={
|
||||||
|
"email": "test@example.com",
|
||||||
|
"password": "wrongpassword",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_nonexistent_user(client: AsyncClient):
|
||||||
|
resp = await client.post("/api/v1/auth/login", json={
|
||||||
|
"email": "nobody@example.com",
|
||||||
|
"password": "password123",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_me_authenticated(client: AsyncClient, registered_user):
|
||||||
|
token = registered_user["access_token"]
|
||||||
|
resp = await client.get("/api/v1/auth/me", headers={
|
||||||
|
"Authorization": f"Bearer {token}",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["email"] == "test@example.com"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_me_unauthenticated(client: AsyncClient):
|
||||||
|
resp = await client.get("/api/v1/auth/me")
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_me_invalid_token(client: AsyncClient):
|
||||||
|
resp = await client.get("/api/v1/auth/me", headers={
|
||||||
|
"Authorization": "Bearer invalid_token_here",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_refresh_token(client: AsyncClient, registered_user):
|
||||||
|
refresh = registered_user["refresh_token"]
|
||||||
|
resp = await client.post("/api/v1/auth/refresh", json={
|
||||||
|
"refresh_token": refresh,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert "access_token" in data
|
||||||
|
assert "refresh_token" in data
|
||||||
|
assert data["refresh_token"] != refresh # rotated
|
||||||
|
|
||||||
|
|
||||||
|
async def test_refresh_invalid_token(client: AsyncClient):
|
||||||
|
resp = await client.post("/api/v1/auth/refresh", json={
|
||||||
|
"refresh_token": "invalid_token",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_logout(client: AsyncClient, registered_user):
|
||||||
|
refresh = registered_user["refresh_token"]
|
||||||
|
resp = await client.post("/api/v1/auth/logout", json={
|
||||||
|
"refresh_token": refresh,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 204
|
||||||
|
|
||||||
|
# Refresh should fail after logout
|
||||||
|
resp = await client.post("/api/v1/auth/refresh", json={
|
||||||
|
"refresh_token": refresh,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 401
|
||||||
31
docker-compose.dev.yml
Normal file
31
docker-compose.dev.yml
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
volumes:
|
||||||
|
- ./backend/app:/app/app
|
||||||
|
- ./backend/scripts:/app/scripts
|
||||||
|
- ./backend/alembic:/app/alembic
|
||||||
|
command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
target: dev
|
||||||
|
volumes:
|
||||||
|
- ./frontend/src:/app/src
|
||||||
|
- ./frontend/public:/app/public
|
||||||
|
- ./frontend/index.html:/app/index.html
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
command: npx vite --host 0.0.0.0 --port 3000
|
||||||
|
|
||||||
|
nginx:
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
47
docker-compose.yml
Normal file
47
docker-compose.yml
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
|
SECRET_KEY: ${SECRET_KEY}
|
||||||
|
BACKEND_CORS_ORIGINS: ${BACKEND_CORS_ORIGINS}
|
||||||
|
ENVIRONMENT: ${ENVIRONMENT}
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES}
|
||||||
|
REFRESH_TOKEN_EXPIRE_DAYS: ${REFRESH_TOKEN_EXPIRE_DAYS}
|
||||||
|
REFRESH_TOKEN_EXPIRE_HOURS: ${REFRESH_TOKEN_EXPIRE_HOURS}
|
||||||
|
FIRST_ADMIN_EMAIL: ${FIRST_ADMIN_EMAIL}
|
||||||
|
FIRST_ADMIN_USERNAME: ${FIRST_ADMIN_USERNAME}
|
||||||
|
FIRST_ADMIN_PASSWORD: ${FIRST_ADMIN_PASSWORD}
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
|
||||||
|
nginx:
|
||||||
|
build: ./nginx
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
- frontend
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
13
frontend/Dockerfile
Normal file
13
frontend/Dockerfile
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
FROM node:20-alpine AS dev
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json* ./
|
||||||
|
RUN npm install
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
FROM dev AS build
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:1.25-alpine AS production
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
EXPOSE 80
|
||||||
16
frontend/components.json
Normal file
16
frontend/components.json
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "default",
|
||||||
|
"rsc": false,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "tailwind.config.ts",
|
||||||
|
"css": "src/index.css",
|
||||||
|
"baseColor": "slate",
|
||||||
|
"cssVariables": true
|
||||||
|
},
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils"
|
||||||
|
}
|
||||||
|
}
|
||||||
12
frontend/index.html
Normal file
12
frontend/index.html
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>AI Assistant</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
11
frontend/nginx.conf
Normal file
11
frontend/nginx.conf
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# SPA fallback
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
4961
frontend/package-lock.json
generated
Normal file
4961
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
frontend/package.json
Normal file
38
frontend/package.json
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"name": "ai-assistant-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"react-router-dom": "^6.28.0",
|
||||||
|
"axios": "^1.7.0",
|
||||||
|
"zustand": "^5.0.0",
|
||||||
|
"@tanstack/react-query": "^5.60.0",
|
||||||
|
"i18next": "^24.0.0",
|
||||||
|
"react-i18next": "^15.1.0",
|
||||||
|
"i18next-http-backend": "^3.0.0",
|
||||||
|
"i18next-browser-languagedetector": "^8.0.0",
|
||||||
|
"lucide-react": "^0.460.0",
|
||||||
|
"clsx": "^2.1.0",
|
||||||
|
"tailwind-merge": "^2.6.0",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"sonner": "^1.7.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"vite": "^6.0.0",
|
||||||
|
"@vitejs/plugin-react": "^4.3.0",
|
||||||
|
"typescript": "^5.6.0",
|
||||||
|
"@types/react": "^18.3.0",
|
||||||
|
"@types/react-dom": "^18.3.0",
|
||||||
|
"tailwindcss": "^3.4.0",
|
||||||
|
"postcss": "^8.4.0",
|
||||||
|
"autoprefixer": "^10.4.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
frontend/postcss.config.js
Normal file
6
frontend/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
};
|
||||||
57
frontend/public/locales/en/translation.json
Normal file
57
frontend/public/locales/en/translation.json
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
"auth": {
|
||||||
|
"login": "Log In",
|
||||||
|
"register": "Sign Up",
|
||||||
|
"email": "Email",
|
||||||
|
"password": "Password",
|
||||||
|
"confirmPassword": "Confirm Password",
|
||||||
|
"username": "Username",
|
||||||
|
"fullName": "Full Name",
|
||||||
|
"rememberMe": "Remember me",
|
||||||
|
"submit": "Submit",
|
||||||
|
"noAccount": "Don't have an account?",
|
||||||
|
"hasAccount": "Already have an account?",
|
||||||
|
"loginTitle": "Welcome Back",
|
||||||
|
"loginSubtitle": "Sign in to your account",
|
||||||
|
"registerTitle": "Create Account",
|
||||||
|
"registerSubtitle": "Get started with your personal AI assistant",
|
||||||
|
"errors": {
|
||||||
|
"invalidCredentials": "Invalid email or password",
|
||||||
|
"emailExists": "User with this email or username already exists",
|
||||||
|
"passwordMismatch": "Passwords do not match",
|
||||||
|
"passwordMinLength": "Password must be at least 8 characters",
|
||||||
|
"usernameFormat": "Username must be 3-50 characters (letters, numbers, _ or -)",
|
||||||
|
"required": "This field is required"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"layout": {
|
||||||
|
"dashboard": "Dashboard",
|
||||||
|
"chats": "Chats",
|
||||||
|
"documents": "Documents",
|
||||||
|
"memory": "Memory",
|
||||||
|
"notifications": "Notifications",
|
||||||
|
"profile": "Profile",
|
||||||
|
"logout": "Log Out",
|
||||||
|
"settings": "Settings",
|
||||||
|
"admin": "Admin",
|
||||||
|
"users": "Users",
|
||||||
|
"context": "Context",
|
||||||
|
"skills": "Skills"
|
||||||
|
},
|
||||||
|
"dashboard": {
|
||||||
|
"welcome": "Welcome, {{name}}",
|
||||||
|
"subtitle": "Your personal AI health assistant"
|
||||||
|
},
|
||||||
|
"common": {
|
||||||
|
"loading": "Loading...",
|
||||||
|
"error": "An error occurred",
|
||||||
|
"notFound": "Page not found",
|
||||||
|
"goHome": "Go to Dashboard",
|
||||||
|
"save": "Save",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"delete": "Delete",
|
||||||
|
"edit": "Edit",
|
||||||
|
"create": "Create",
|
||||||
|
"search": "Search"
|
||||||
|
}
|
||||||
|
}
|
||||||
57
frontend/public/locales/ru/translation.json
Normal file
57
frontend/public/locales/ru/translation.json
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
"auth": {
|
||||||
|
"login": "Войти",
|
||||||
|
"register": "Регистрация",
|
||||||
|
"email": "Email",
|
||||||
|
"password": "Пароль",
|
||||||
|
"confirmPassword": "Подтвердите пароль",
|
||||||
|
"username": "Имя пользователя",
|
||||||
|
"fullName": "Полное имя",
|
||||||
|
"rememberMe": "Запомнить меня",
|
||||||
|
"submit": "Отправить",
|
||||||
|
"noAccount": "Нет аккаунта?",
|
||||||
|
"hasAccount": "Уже есть аккаунт?",
|
||||||
|
"loginTitle": "С возвращением",
|
||||||
|
"loginSubtitle": "Войдите в свой аккаунт",
|
||||||
|
"registerTitle": "Создать аккаунт",
|
||||||
|
"registerSubtitle": "Начните работу с персональным ИИ-ассистентом",
|
||||||
|
"errors": {
|
||||||
|
"invalidCredentials": "Неверный email или пароль",
|
||||||
|
"emailExists": "Пользователь с таким email или именем уже существует",
|
||||||
|
"passwordMismatch": "Пароли не совпадают",
|
||||||
|
"passwordMinLength": "Пароль должен содержать минимум 8 символов",
|
||||||
|
"usernameFormat": "Имя пользователя: 3-50 символов (буквы, цифры, _ или -)",
|
||||||
|
"required": "Это поле обязательно"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"layout": {
|
||||||
|
"dashboard": "Главная",
|
||||||
|
"chats": "Чаты",
|
||||||
|
"documents": "Документы",
|
||||||
|
"memory": "Память",
|
||||||
|
"notifications": "Уведомления",
|
||||||
|
"profile": "Профиль",
|
||||||
|
"logout": "Выйти",
|
||||||
|
"settings": "Настройки",
|
||||||
|
"admin": "Администрирование",
|
||||||
|
"users": "Пользователи",
|
||||||
|
"context": "Контекст",
|
||||||
|
"skills": "Навыки"
|
||||||
|
},
|
||||||
|
"dashboard": {
|
||||||
|
"welcome": "Добро пожаловать, {{name}}",
|
||||||
|
"subtitle": "Ваш персональный ИИ-ассистент по здоровью"
|
||||||
|
},
|
||||||
|
"common": {
|
||||||
|
"loading": "Загрузка...",
|
||||||
|
"error": "Произошла ошибка",
|
||||||
|
"notFound": "Страница не найдена",
|
||||||
|
"goHome": "На главную",
|
||||||
|
"save": "Сохранить",
|
||||||
|
"cancel": "Отмена",
|
||||||
|
"delete": "Удалить",
|
||||||
|
"edit": "Редактировать",
|
||||||
|
"create": "Создать",
|
||||||
|
"search": "Поиск"
|
||||||
|
}
|
||||||
|
}
|
||||||
19
frontend/src/App.tsx
Normal file
19
frontend/src/App.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Suspense } from "react";
|
||||||
|
import { RouterProvider } from "react-router-dom";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { ThemeProvider } from "@/components/shared/theme-provider";
|
||||||
|
import { queryClient } from "@/lib/query-client";
|
||||||
|
import { router } from "@/routes";
|
||||||
|
import "@/i18n";
|
||||||
|
|
||||||
|
export function App() {
|
||||||
|
return (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ThemeProvider>
|
||||||
|
<Suspense fallback={<div className="flex h-screen items-center justify-center">Loading...</div>}>
|
||||||
|
<RouterProvider router={router} />
|
||||||
|
</Suspense>
|
||||||
|
</ThemeProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
68
frontend/src/api/auth.ts
Normal file
68
frontend/src/api/auth.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import api from "./client";
|
||||||
|
|
||||||
|
export interface UserResponse {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
username: string;
|
||||||
|
full_name: string | null;
|
||||||
|
role: string;
|
||||||
|
is_active: boolean;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthResponse {
|
||||||
|
user: UserResponse;
|
||||||
|
access_token: string;
|
||||||
|
refresh_token: string;
|
||||||
|
token_type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TokenResponse {
|
||||||
|
access_token: string;
|
||||||
|
refresh_token: string;
|
||||||
|
token_type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function login(
|
||||||
|
email: string,
|
||||||
|
password: string,
|
||||||
|
remember_me: boolean
|
||||||
|
): Promise<AuthResponse> {
|
||||||
|
const { data } = await api.post<AuthResponse>("/auth/login", {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
remember_me,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function register(
|
||||||
|
email: string,
|
||||||
|
username: string,
|
||||||
|
password: string,
|
||||||
|
full_name?: string
|
||||||
|
): Promise<AuthResponse> {
|
||||||
|
const { data } = await api.post<AuthResponse>("/auth/register", {
|
||||||
|
email,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
full_name: full_name || undefined,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function refresh(refreshToken: string): Promise<TokenResponse> {
|
||||||
|
const { data } = await api.post<TokenResponse>("/auth/refresh", {
|
||||||
|
refresh_token: refreshToken,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logout(refreshToken: string): Promise<void> {
|
||||||
|
await api.post("/auth/logout", { refresh_token: refreshToken });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMe(): Promise<UserResponse> {
|
||||||
|
const { data } = await api.get<UserResponse>("/auth/me");
|
||||||
|
return data;
|
||||||
|
}
|
||||||
83
frontend/src/api/client.ts
Normal file
83
frontend/src/api/client.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
|
||||||
|
const api = axios.create({
|
||||||
|
baseURL: "/api/v1",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attach access token
|
||||||
|
api.interceptors.request.use((config) => {
|
||||||
|
const token = useAuthStore.getState().accessToken;
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Auto-refresh on 401
|
||||||
|
let isRefreshing = false;
|
||||||
|
let failedQueue: Array<{
|
||||||
|
resolve: (token: string) => void;
|
||||||
|
reject: (error: unknown) => void;
|
||||||
|
}> = [];
|
||||||
|
|
||||||
|
function processQueue(error: unknown, token: string | null) {
|
||||||
|
failedQueue.forEach(({ resolve, reject }) => {
|
||||||
|
if (error) reject(error);
|
||||||
|
else resolve(token!);
|
||||||
|
});
|
||||||
|
failedQueue = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
api.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
async (error) => {
|
||||||
|
const originalRequest = error.config;
|
||||||
|
|
||||||
|
if (error.response?.status !== 401 || originalRequest._retry) {
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRefreshing) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
failedQueue.push({
|
||||||
|
resolve: (token: string) => {
|
||||||
|
originalRequest.headers.Authorization = `Bearer ${token}`;
|
||||||
|
resolve(api(originalRequest));
|
||||||
|
},
|
||||||
|
reject,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
originalRequest._retry = true;
|
||||||
|
isRefreshing = true;
|
||||||
|
|
||||||
|
const refreshToken = useAuthStore.getState().refreshToken;
|
||||||
|
if (!refreshToken) {
|
||||||
|
useAuthStore.getState().clearAuth();
|
||||||
|
window.location.href = "/login";
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data } = await axios.post("/api/v1/auth/refresh", {
|
||||||
|
refresh_token: refreshToken,
|
||||||
|
});
|
||||||
|
useAuthStore.getState().setTokens(data.access_token, data.refresh_token);
|
||||||
|
processQueue(null, data.access_token);
|
||||||
|
originalRequest.headers.Authorization = `Bearer ${data.access_token}`;
|
||||||
|
return api(originalRequest);
|
||||||
|
} catch (refreshError) {
|
||||||
|
processQueue(refreshError, null);
|
||||||
|
useAuthStore.getState().clearAuth();
|
||||||
|
window.location.href = "/login";
|
||||||
|
return Promise.reject(refreshError);
|
||||||
|
} finally {
|
||||||
|
isRefreshing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export default api;
|
||||||
103
frontend/src/components/auth/login-form.tsx
Normal file
103
frontend/src/components/auth/login-form.tsx
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { login } from "@/api/auth";
|
||||||
|
|
||||||
|
export function LoginForm() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const setAuth = useAuthStore((s) => s.setAuth);
|
||||||
|
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [rememberMe, setRememberMe] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError("");
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await login(email, password, rememberMe);
|
||||||
|
setAuth(data.user, data.access_token, data.refresh_token);
|
||||||
|
navigate("/");
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const msg =
|
||||||
|
(err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||
|
||||||
|
t("auth.errors.invalidCredentials");
|
||||||
|
setError(msg);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-destructive/10 px-4 py-3 text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="email" className="text-sm font-medium">
|
||||||
|
{t("auth.email")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
placeholder="name@example.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="password" className="text-sm font-medium">
|
||||||
|
{t("auth.password")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
id="remember"
|
||||||
|
type="checkbox"
|
||||||
|
checked={rememberMe}
|
||||||
|
onChange={(e) => setRememberMe(e.target.checked)}
|
||||||
|
className="h-4 w-4 rounded border-input"
|
||||||
|
/>
|
||||||
|
<label htmlFor="remember" className="text-sm text-muted-foreground">
|
||||||
|
{t("auth.rememberMe")}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
|
||||||
|
>
|
||||||
|
{loading ? t("common.loading") : t("auth.login")}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
{t("auth.noAccount")}{" "}
|
||||||
|
<Link to="/register" className="text-primary hover:underline">
|
||||||
|
{t("auth.register")}
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
150
frontend/src/components/auth/register-form.tsx
Normal file
150
frontend/src/components/auth/register-form.tsx
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { register } from "@/api/auth";
|
||||||
|
|
||||||
|
export function RegisterForm() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const setAuth = useAuthStore((s) => s.setAuth);
|
||||||
|
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
const [fullName, setFullName] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
if (password.length < 8) {
|
||||||
|
setError(t("auth.errors.passwordMinLength"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
setError(t("auth.errors.passwordMismatch"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!/^[a-zA-Z0-9_-]{3,50}$/.test(username)) {
|
||||||
|
setError(t("auth.errors.usernameFormat"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await register(email, username, password, fullName || undefined);
|
||||||
|
setAuth(data.user, data.access_token, data.refresh_token);
|
||||||
|
navigate("/");
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const msg =
|
||||||
|
(err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||
|
||||||
|
t("auth.errors.emailExists");
|
||||||
|
setError(msg);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-destructive/10 px-4 py-3 text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="email" className="text-sm font-medium">
|
||||||
|
{t("auth.email")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
placeholder="name@example.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="username" className="text-sm font-medium">
|
||||||
|
{t("auth.username")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="username"
|
||||||
|
type="text"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
required
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="fullName" className="text-sm font-medium">
|
||||||
|
{t("auth.fullName")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="fullName"
|
||||||
|
type="text"
|
||||||
|
value={fullName}
|
||||||
|
onChange={(e) => setFullName(e.target.value)}
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="password" className="text-sm font-medium">
|
||||||
|
{t("auth.password")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="confirmPassword" className="text-sm font-medium">
|
||||||
|
{t("auth.confirmPassword")}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
|
||||||
|
>
|
||||||
|
{loading ? t("common.loading") : t("auth.register")}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
{t("auth.hasAccount")}{" "}
|
||||||
|
<Link to="/login" className="text-primary hover:underline">
|
||||||
|
{t("auth.login")}
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
frontend/src/components/layout/app-layout.tsx
Normal file
17
frontend/src/components/layout/app-layout.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { Outlet } from "react-router-dom";
|
||||||
|
import { Sidebar } from "./sidebar";
|
||||||
|
import { Header } from "./header";
|
||||||
|
|
||||||
|
export function AppLayout() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen overflow-hidden">
|
||||||
|
<Sidebar />
|
||||||
|
<div className="flex flex-1 flex-col overflow-hidden">
|
||||||
|
<Header />
|
||||||
|
<main className="flex-1 overflow-y-auto p-6">
|
||||||
|
<Outlet />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
69
frontend/src/components/layout/header.tsx
Normal file
69
frontend/src/components/layout/header.tsx
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { Menu, Sun, Moon, LogOut, User } from "lucide-react";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { useUIStore } from "@/stores/ui-store";
|
||||||
|
import { LanguageToggle } from "@/components/shared/language-toggle";
|
||||||
|
import { logout as logoutApi } from "@/api/auth";
|
||||||
|
|
||||||
|
export function Header() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const { refreshToken, clearAuth } = useAuthStore();
|
||||||
|
const { theme, setTheme, toggleSidebar } = useUIStore();
|
||||||
|
|
||||||
|
const handleLogout = async () => {
|
||||||
|
try {
|
||||||
|
if (refreshToken) await logoutApi(refreshToken);
|
||||||
|
} finally {
|
||||||
|
clearAuth();
|
||||||
|
navigate("/login");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
if (theme === "light") setTheme("dark");
|
||||||
|
else if (theme === "dark") setTheme("system");
|
||||||
|
else setTheme("light");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="flex h-14 items-center gap-4 border-b bg-card px-4">
|
||||||
|
<button
|
||||||
|
onClick={toggleSidebar}
|
||||||
|
className="rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
<Menu className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex-1" />
|
||||||
|
|
||||||
|
<LanguageToggle />
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={toggleTheme}
|
||||||
|
className="rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
|
||||||
|
title={`Theme: ${theme}`}
|
||||||
|
>
|
||||||
|
{theme === "dark" ? <Moon className="h-5 w-5" /> : <Sun className="h-5 w-5" />}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 border-l pl-4">
|
||||||
|
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-primary">
|
||||||
|
<User className="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
<span className="hidden text-sm font-medium sm:block">
|
||||||
|
{user?.full_name || user?.username}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-destructive transition-colors"
|
||||||
|
title={t("layout.logout")}
|
||||||
|
>
|
||||||
|
<LogOut className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
99
frontend/src/components/layout/sidebar.tsx
Normal file
99
frontend/src/components/layout/sidebar.tsx
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { NavLink } from "react-router-dom";
|
||||||
|
import {
|
||||||
|
LayoutDashboard,
|
||||||
|
MessageSquare,
|
||||||
|
FileText,
|
||||||
|
Brain,
|
||||||
|
Bell,
|
||||||
|
Shield,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { useUIStore } from "@/stores/ui-store";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const navItems = [
|
||||||
|
{ key: "dashboard", to: "/", icon: LayoutDashboard, enabled: true },
|
||||||
|
{ key: "chats", to: "/chat", icon: MessageSquare, enabled: false },
|
||||||
|
{ key: "documents", to: "/documents", icon: FileText, enabled: false },
|
||||||
|
{ key: "memory", to: "/memory", icon: Brain, enabled: false },
|
||||||
|
{ key: "notifications", to: "/notifications", icon: Bell, enabled: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function Sidebar() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const sidebarOpen = useUIStore((s) => s.sidebarOpen);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside
|
||||||
|
className={cn(
|
||||||
|
"flex h-full flex-col border-r bg-card transition-all duration-300",
|
||||||
|
sidebarOpen ? "w-60" : "w-16"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex h-14 items-center border-b px-4">
|
||||||
|
{sidebarOpen && (
|
||||||
|
<span className="text-lg font-semibold text-primary">AI Assistant</span>
|
||||||
|
)}
|
||||||
|
{!sidebarOpen && (
|
||||||
|
<span className="text-lg font-semibold text-primary mx-auto">AI</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav className="flex-1 space-y-1 p-2">
|
||||||
|
{navItems.map((item) => {
|
||||||
|
const Icon = item.icon;
|
||||||
|
if (!item.enabled) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.key}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground/50 cursor-not-allowed",
|
||||||
|
!sidebarOpen && "justify-center px-2"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="h-5 w-5 shrink-0" />
|
||||||
|
{sidebarOpen && <span>{t(`layout.${item.key}`)}</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<NavLink
|
||||||
|
key={item.key}
|
||||||
|
to={item.to}
|
||||||
|
end
|
||||||
|
className={({ isActive }) =>
|
||||||
|
cn(
|
||||||
|
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors",
|
||||||
|
isActive
|
||||||
|
? "bg-primary/10 text-primary font-medium"
|
||||||
|
: "text-muted-foreground hover:bg-accent hover:text-foreground",
|
||||||
|
!sidebarOpen && "justify-center px-2"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Icon className="h-5 w-5 shrink-0" />
|
||||||
|
{sidebarOpen && <span>{t(`layout.${item.key}`)}</span>}
|
||||||
|
</NavLink>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{user?.role === "admin" && (
|
||||||
|
<div className="border-t p-2">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground/50 cursor-not-allowed",
|
||||||
|
!sidebarOpen && "justify-center px-2"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Shield className="h-5 w-5 shrink-0" />
|
||||||
|
{sidebarOpen && <span>{t("layout.admin")}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
22
frontend/src/components/shared/language-toggle.tsx
Normal file
22
frontend/src/components/shared/language-toggle.tsx
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Languages } from "lucide-react";
|
||||||
|
|
||||||
|
export function LanguageToggle() {
|
||||||
|
const { i18n } = useTranslation();
|
||||||
|
|
||||||
|
const toggle = () => {
|
||||||
|
const next = i18n.language === "ru" ? "en" : "ru";
|
||||||
|
i18n.changeLanguage(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={toggle}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
|
||||||
|
title={i18n.language === "ru" ? "Switch to English" : "Переключить на русский"}
|
||||||
|
>
|
||||||
|
<Languages className="h-4 w-4" />
|
||||||
|
<span className="uppercase">{i18n.language === "ru" ? "en" : "ru"}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
12
frontend/src/components/shared/protected-route.tsx
Normal file
12
frontend/src/components/shared/protected-route.tsx
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Navigate, Outlet } from "react-router-dom";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
|
||||||
|
export function ProtectedRoute() {
|
||||||
|
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Outlet />;
|
||||||
|
}
|
||||||
20
frontend/src/components/shared/theme-provider.tsx
Normal file
20
frontend/src/components/shared/theme-provider.tsx
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import { useUIStore } from "@/stores/ui-store";
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const theme = useUIStore((s) => s.theme);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
root.classList.remove("light", "dark");
|
||||||
|
|
||||||
|
if (theme === "system") {
|
||||||
|
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||||
|
root.classList.add(systemDark ? "dark" : "light");
|
||||||
|
} else {
|
||||||
|
root.classList.add(theme);
|
||||||
|
}
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
25
frontend/src/i18n.ts
Normal file
25
frontend/src/i18n.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import i18n from "i18next";
|
||||||
|
import { initReactI18next } from "react-i18next";
|
||||||
|
import HttpBackend from "i18next-http-backend";
|
||||||
|
import LanguageDetector from "i18next-browser-languagedetector";
|
||||||
|
|
||||||
|
i18n
|
||||||
|
.use(HttpBackend)
|
||||||
|
.use(LanguageDetector)
|
||||||
|
.use(initReactI18next)
|
||||||
|
.init({
|
||||||
|
fallbackLng: "en",
|
||||||
|
supportedLngs: ["en", "ru"],
|
||||||
|
interpolation: {
|
||||||
|
escapeValue: false,
|
||||||
|
},
|
||||||
|
backend: {
|
||||||
|
loadPath: "/locales/{{lng}}/translation.json",
|
||||||
|
},
|
||||||
|
detection: {
|
||||||
|
order: ["localStorage", "navigator"],
|
||||||
|
caches: ["localStorage"],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default i18n;
|
||||||
59
frontend/src/index.css
Normal file
59
frontend/src/index.css
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
:root {
|
||||||
|
--background: 210 40% 98%;
|
||||||
|
--foreground: 222 47% 11%;
|
||||||
|
--card: 0 0% 100%;
|
||||||
|
--card-foreground: 222 47% 11%;
|
||||||
|
--popover: 0 0% 100%;
|
||||||
|
--popover-foreground: 222 47% 11%;
|
||||||
|
--primary: 198 70% 40%;
|
||||||
|
--primary-foreground: 210 40% 98%;
|
||||||
|
--secondary: 210 40% 96%;
|
||||||
|
--secondary-foreground: 222 47% 11%;
|
||||||
|
--muted: 210 40% 96%;
|
||||||
|
--muted-foreground: 215 16% 47%;
|
||||||
|
--accent: 210 40% 96%;
|
||||||
|
--accent-foreground: 222 47% 11%;
|
||||||
|
--destructive: 0 84% 60%;
|
||||||
|
--destructive-foreground: 210 40% 98%;
|
||||||
|
--border: 214 32% 91%;
|
||||||
|
--input: 214 32% 91%;
|
||||||
|
--ring: 198 70% 40%;
|
||||||
|
--radius: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: 222 47% 11%;
|
||||||
|
--foreground: 210 40% 98%;
|
||||||
|
--card: 222 47% 13%;
|
||||||
|
--card-foreground: 210 40% 98%;
|
||||||
|
--popover: 222 47% 13%;
|
||||||
|
--popover-foreground: 210 40% 98%;
|
||||||
|
--primary: 198 70% 50%;
|
||||||
|
--primary-foreground: 222 47% 11%;
|
||||||
|
--secondary: 217 33% 17%;
|
||||||
|
--secondary-foreground: 210 40% 98%;
|
||||||
|
--muted: 217 33% 17%;
|
||||||
|
--muted-foreground: 215 20% 65%;
|
||||||
|
--accent: 217 33% 17%;
|
||||||
|
--accent-foreground: 210 40% 98%;
|
||||||
|
--destructive: 0 63% 31%;
|
||||||
|
--destructive-foreground: 210 40% 98%;
|
||||||
|
--border: 217 33% 17%;
|
||||||
|
--input: 217 33% 17%;
|
||||||
|
--ring: 198 70% 50%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground;
|
||||||
|
}
|
||||||
|
}
|
||||||
11
frontend/src/lib/query-client.ts
Normal file
11
frontend/src/lib/query-client.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { QueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
export const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
retry: 1,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
6
frontend/src/lib/utils.ts
Normal file
6
frontend/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { type ClassValue, clsx } from "clsx";
|
||||||
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs));
|
||||||
|
}
|
||||||
10
frontend/src/main.tsx
Normal file
10
frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import React from "react";
|
||||||
|
import ReactDOM from "react-dom/client";
|
||||||
|
import { App } from "./App";
|
||||||
|
import "./index.css";
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
33
frontend/src/pages/dashboard.tsx
Normal file
33
frontend/src/pages/dashboard.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
|
||||||
|
export function DashboardPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight">
|
||||||
|
{t("dashboard.welcome", { name: user?.full_name || user?.username })}
|
||||||
|
</h1>
|
||||||
|
<p className="text-muted-foreground">{t("dashboard.subtitle")}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<div className="rounded-xl border bg-card p-6 shadow-sm">
|
||||||
|
<h3 className="text-sm font-medium text-muted-foreground">{t("layout.chats")}</h3>
|
||||||
|
<p className="mt-2 text-3xl font-bold">0</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl border bg-card p-6 shadow-sm">
|
||||||
|
<h3 className="text-sm font-medium text-muted-foreground">{t("layout.documents")}</h3>
|
||||||
|
<p className="mt-2 text-3xl font-bold">0</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl border bg-card p-6 shadow-sm">
|
||||||
|
<h3 className="text-sm font-medium text-muted-foreground">{t("layout.notifications")}</h3>
|
||||||
|
<p className="mt-2 text-3xl font-bold">0</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
27
frontend/src/pages/login.tsx
Normal file
27
frontend/src/pages/login.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Navigate } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { LoginForm } from "@/components/auth/login-form";
|
||||||
|
import { LanguageToggle } from "@/components/shared/language-toggle";
|
||||||
|
|
||||||
|
export function LoginPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
|
||||||
|
|
||||||
|
if (isAuthenticated) return <Navigate to="/" replace />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-background px-4">
|
||||||
|
<div className="absolute right-4 top-4">
|
||||||
|
<LanguageToggle />
|
||||||
|
</div>
|
||||||
|
<div className="w-full max-w-md space-y-6 rounded-xl border bg-card p-8 shadow-sm">
|
||||||
|
<div className="space-y-2 text-center">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight">{t("auth.loginTitle")}</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{t("auth.loginSubtitle")}</p>
|
||||||
|
</div>
|
||||||
|
<LoginForm />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
19
frontend/src/pages/not-found.tsx
Normal file
19
frontend/src/pages/not-found.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
export function NotFoundPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col items-center justify-center bg-background">
|
||||||
|
<h1 className="text-6xl font-bold text-muted-foreground">404</h1>
|
||||||
|
<p className="mt-4 text-lg text-muted-foreground">{t("common.notFound")}</p>
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="mt-6 inline-flex h-10 items-center justify-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
|
||||||
|
>
|
||||||
|
{t("common.goHome")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
27
frontend/src/pages/register.tsx
Normal file
27
frontend/src/pages/register.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Navigate } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { RegisterForm } from "@/components/auth/register-form";
|
||||||
|
import { LanguageToggle } from "@/components/shared/language-toggle";
|
||||||
|
|
||||||
|
export function RegisterPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
|
||||||
|
|
||||||
|
if (isAuthenticated) return <Navigate to="/" replace />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-background px-4">
|
||||||
|
<div className="absolute right-4 top-4">
|
||||||
|
<LanguageToggle />
|
||||||
|
</div>
|
||||||
|
<div className="w-full max-w-md space-y-6 rounded-xl border bg-card p-8 shadow-sm">
|
||||||
|
<div className="space-y-2 text-center">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight">{t("auth.registerTitle")}</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{t("auth.registerSubtitle")}</p>
|
||||||
|
</div>
|
||||||
|
<RegisterForm />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
33
frontend/src/routes.tsx
Normal file
33
frontend/src/routes.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { createBrowserRouter } from "react-router-dom";
|
||||||
|
import { ProtectedRoute } from "@/components/shared/protected-route";
|
||||||
|
import { AppLayout } from "@/components/layout/app-layout";
|
||||||
|
import { LoginPage } from "@/pages/login";
|
||||||
|
import { RegisterPage } from "@/pages/register";
|
||||||
|
import { DashboardPage } from "@/pages/dashboard";
|
||||||
|
import { NotFoundPage } from "@/pages/not-found";
|
||||||
|
|
||||||
|
export const router = createBrowserRouter([
|
||||||
|
{
|
||||||
|
path: "/login",
|
||||||
|
element: <LoginPage />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/register",
|
||||||
|
element: <RegisterPage />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
element: <ProtectedRoute />,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
element: <AppLayout />,
|
||||||
|
children: [
|
||||||
|
{ index: true, element: <DashboardPage /> },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "*",
|
||||||
|
element: <NotFoundPage />,
|
||||||
|
},
|
||||||
|
]);
|
||||||
41
frontend/src/stores/auth-store.ts
Normal file
41
frontend/src/stores/auth-store.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import { persist } from "zustand/middleware";
|
||||||
|
import type { UserResponse } from "@/api/auth";
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
user: UserResponse | null;
|
||||||
|
accessToken: string | null;
|
||||||
|
refreshToken: string | null;
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
setAuth: (user: UserResponse, accessToken: string, refreshToken: string) => void;
|
||||||
|
setTokens: (accessToken: string, refreshToken: string) => void;
|
||||||
|
setUser: (user: UserResponse) => void;
|
||||||
|
clearAuth: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAuthStore = create<AuthState>()(
|
||||||
|
persist(
|
||||||
|
(set) => ({
|
||||||
|
user: null,
|
||||||
|
accessToken: null,
|
||||||
|
refreshToken: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
setAuth: (user, accessToken, refreshToken) =>
|
||||||
|
set({ user, accessToken, refreshToken, isAuthenticated: true }),
|
||||||
|
setTokens: (accessToken, refreshToken) =>
|
||||||
|
set({ accessToken, refreshToken }),
|
||||||
|
setUser: (user) => set({ user }),
|
||||||
|
clearAuth: () =>
|
||||||
|
set({ user: null, accessToken: null, refreshToken: null, isAuthenticated: false }),
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
name: "auth-storage",
|
||||||
|
partialize: (state) => ({
|
||||||
|
user: state.user,
|
||||||
|
accessToken: state.accessToken,
|
||||||
|
refreshToken: state.refreshToken,
|
||||||
|
isAuthenticated: state.isAuthenticated,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
28
frontend/src/stores/ui-store.ts
Normal file
28
frontend/src/stores/ui-store.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import { persist } from "zustand/middleware";
|
||||||
|
|
||||||
|
type Theme = "light" | "dark" | "system";
|
||||||
|
|
||||||
|
interface UIState {
|
||||||
|
sidebarOpen: boolean;
|
||||||
|
theme: Theme;
|
||||||
|
toggleSidebar: () => void;
|
||||||
|
setSidebarOpen: (open: boolean) => void;
|
||||||
|
setTheme: (theme: Theme) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useUIStore = create<UIState>()(
|
||||||
|
persist(
|
||||||
|
(set) => ({
|
||||||
|
sidebarOpen: true,
|
||||||
|
theme: "system",
|
||||||
|
toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
|
||||||
|
setSidebarOpen: (open) => set({ sidebarOpen: open }),
|
||||||
|
setTheme: (theme) => set({ theme }),
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
name: "ui-storage",
|
||||||
|
partialize: (state) => ({ theme: state.theme }),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
1
frontend/src/vite-env.d.ts
vendored
Normal file
1
frontend/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
51
frontend/tailwind.config.ts
Normal file
51
frontend/tailwind.config.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import type { Config } from "tailwindcss";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
darkMode: "class",
|
||||||
|
content: ["./index.html", "./src/**/*.{ts,tsx}"],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
border: "hsl(var(--border))",
|
||||||
|
input: "hsl(var(--input))",
|
||||||
|
ring: "hsl(var(--ring))",
|
||||||
|
background: "hsl(var(--background))",
|
||||||
|
foreground: "hsl(var(--foreground))",
|
||||||
|
primary: {
|
||||||
|
DEFAULT: "hsl(var(--primary))",
|
||||||
|
foreground: "hsl(var(--primary-foreground))",
|
||||||
|
},
|
||||||
|
secondary: {
|
||||||
|
DEFAULT: "hsl(var(--secondary))",
|
||||||
|
foreground: "hsl(var(--secondary-foreground))",
|
||||||
|
},
|
||||||
|
destructive: {
|
||||||
|
DEFAULT: "hsl(var(--destructive))",
|
||||||
|
foreground: "hsl(var(--destructive-foreground))",
|
||||||
|
},
|
||||||
|
muted: {
|
||||||
|
DEFAULT: "hsl(var(--muted))",
|
||||||
|
foreground: "hsl(var(--muted-foreground))",
|
||||||
|
},
|
||||||
|
accent: {
|
||||||
|
DEFAULT: "hsl(var(--accent))",
|
||||||
|
foreground: "hsl(var(--accent-foreground))",
|
||||||
|
},
|
||||||
|
popover: {
|
||||||
|
DEFAULT: "hsl(var(--popover))",
|
||||||
|
foreground: "hsl(var(--popover-foreground))",
|
||||||
|
},
|
||||||
|
card: {
|
||||||
|
DEFAULT: "hsl(var(--card))",
|
||||||
|
foreground: "hsl(var(--card-foreground))",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
borderRadius: {
|
||||||
|
lg: "var(--radius)",
|
||||||
|
md: "calc(var(--radius) - 2px)",
|
||||||
|
sm: "calc(var(--radius) - 4px)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
} satisfies Config;
|
||||||
24
frontend/tsconfig.json
Normal file
24
frontend/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src", "vite.config.ts"]
|
||||||
|
}
|
||||||
19
frontend/tsconfig.node.json
Normal file
19
frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"composite": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
24
frontend/vite.config.ts
Normal file
24
frontend/vite.config.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
"@": path.resolve(__dirname, "./src"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
"/api": {
|
||||||
|
target: "http://localhost:8000",
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
"/ws": {
|
||||||
|
target: "http://localhost:8000",
|
||||||
|
ws: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
3
nginx/Dockerfile
Normal file
3
nginx/Dockerfile
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
FROM nginx:1.25-alpine
|
||||||
|
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
49
nginx/nginx.conf
Normal file
49
nginx/nginx.conf
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
upstream backend {
|
||||||
|
server backend:8000;
|
||||||
|
}
|
||||||
|
|
||||||
|
upstream frontend {
|
||||||
|
server frontend:80;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
client_max_body_size 50M;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
|
||||||
|
gzip_min_length 256;
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
|
||||||
|
# API and WebSocket
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /ws/ {
|
||||||
|
proxy_pass http://backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
location / {
|
||||||
|
proxy_pass http://frontend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
285
plans/phase-1-foundation.md
Normal file
285
plans/phase-1-foundation.md
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
# Phase 1: Foundation — Subplan
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Stand up the monorepo skeleton with Docker Compose orchestration, a working FastAPI backend with database migrations and JWT authentication, a React frontend shell with auth pages and protected routing, and an admin seed script — so that a user can register, log in, see a dashboard shell, and an admin account exists.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Git repository initialized (done)
|
||||||
|
- Docker and Docker Compose installed on the development machine
|
||||||
|
- Node.js 20+ and Python 3.12+ available locally for development outside containers
|
||||||
|
- `GeneralPlan.md`, `README.md`, `.gitignore` already in repo (done)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Database Schema (Phase 1)
|
||||||
|
|
||||||
|
### `users` table
|
||||||
|
|
||||||
|
| Column | Type | Constraints |
|
||||||
|
|---|---|---|
|
||||||
|
| id | UUID | PK, default gen_random_uuid() |
|
||||||
|
| email | VARCHAR(255) | UNIQUE, NOT NULL |
|
||||||
|
| username | VARCHAR(100) | UNIQUE, NOT NULL |
|
||||||
|
| hashed_password | VARCHAR(255) | NOT NULL |
|
||||||
|
| full_name | VARCHAR(255) | NULL |
|
||||||
|
| role | VARCHAR(20) | NOT NULL, default 'user', CHECK IN ('user','admin') |
|
||||||
|
| is_active | BOOLEAN | NOT NULL, default true |
|
||||||
|
| max_chats | INTEGER | NOT NULL, default 10 |
|
||||||
|
| oauth_provider | VARCHAR(50) | NULL |
|
||||||
|
| oauth_provider_id | VARCHAR(255) | NULL |
|
||||||
|
| telegram_chat_id | BIGINT | NULL |
|
||||||
|
| avatar_url | VARCHAR(500) | NULL |
|
||||||
|
| created_at | TIMESTAMPTZ | NOT NULL, default now() |
|
||||||
|
| updated_at | TIMESTAMPTZ | NOT NULL, default now(), on-update trigger |
|
||||||
|
|
||||||
|
Indexes: `ix_users_email` (unique), `ix_users_username` (unique).
|
||||||
|
|
||||||
|
### `sessions` table
|
||||||
|
|
||||||
|
| Column | Type | Constraints |
|
||||||
|
|---|---|---|
|
||||||
|
| id | UUID | PK, default gen_random_uuid() |
|
||||||
|
| user_id | UUID | FK -> users.id ON DELETE CASCADE, NOT NULL |
|
||||||
|
| refresh_token_hash | VARCHAR(255) | NOT NULL |
|
||||||
|
| device_info | VARCHAR(500) | NULL |
|
||||||
|
| ip_address | VARCHAR(45) | NULL |
|
||||||
|
| expires_at | TIMESTAMPTZ | NOT NULL |
|
||||||
|
| created_at | TIMESTAMPTZ | NOT NULL, default now() |
|
||||||
|
|
||||||
|
Indexes: `ix_sessions_user_id`, `ix_sessions_refresh_token_hash`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API Endpoint Signatures (Phase 1 Auth)
|
||||||
|
|
||||||
|
All under `/api/v1/auth/`.
|
||||||
|
|
||||||
|
| Method | Path | Request Body | Response | Notes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| POST | `/register` | `{ email, username, password, full_name? }` | `{ user, access_token, refresh_token }` | Creates user + session. 201 |
|
||||||
|
| POST | `/login` | `{ email, password, remember_me?: bool }` | `{ user, access_token, refresh_token }` | `remember_me` controls refresh expiry (30d vs 24h). 200 |
|
||||||
|
| POST | `/refresh` | `{ refresh_token }` | `{ access_token, refresh_token }` | Rotates refresh token (old invalidated). 200 |
|
||||||
|
| POST | `/logout` | `{ refresh_token }` | `204 No Content` | Deletes session row |
|
||||||
|
| GET | `/me` | — | `UserResponse` | Requires valid access token. 200 |
|
||||||
|
|
||||||
|
**Token details:**
|
||||||
|
|
||||||
|
- Access token: JWT, HS256, 15-minute expiry, payload: `{ sub: user_id, role, exp, iat, jti }`
|
||||||
|
- Refresh token: opaque 64-byte hex string; only its SHA-256 hash is stored in `sessions.refresh_token_hash`
|
||||||
|
- Password hashing: bcrypt via `passlib[bcrypt]`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frontend Route Structure (Phase 1)
|
||||||
|
|
||||||
|
| Path | Component | Auth Required | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `/login` | LoginPage | No | Redirects to `/` if already authenticated |
|
||||||
|
| `/register` | RegisterPage | No | Redirects to `/` if already authenticated |
|
||||||
|
| `/` | DashboardPage | Yes | Wrapped in AppLayout (sidebar + header) |
|
||||||
|
| `*` | NotFoundPage | No | 404 fallback |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
|
||||||
|
### A. Project Infrastructure & Docker (Tasks 1–6)
|
||||||
|
|
||||||
|
- [x] **A1.** Create root-level config files: `.env.example` (all env vars: `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB`, `SECRET_KEY`, `BACKEND_CORS_ORIGINS`, `FIRST_ADMIN_EMAIL`, `FIRST_ADMIN_PASSWORD`, `FIRST_ADMIN_USERNAME`), `docker-compose.yml`, `docker-compose.dev.yml` (volume mounts + hot reload).
|
||||||
|
|
||||||
|
- [x] **A2.** Create `nginx/nginx.conf` with reverse proxy rules: `/api/*` → `backend:8000`, `/` → `frontend:80`. Include WebSocket upgrade headers for future `/ws/*`. Add gzip, security headers, `client_max_body_size 50M`.
|
||||||
|
|
||||||
|
- [x] **A.** Create `nginx/Dockerfile` (FROM nginx:1.25-alpine, copy nginx.conf).
|
||||||
|
|
||||||
|
- [x] **A.** Create `backend/Dockerfile` (Python 3.12-slim, install deps from pyproject.toml, run uvicorn). Create `backend/pyproject.toml` with dependencies: fastapi, uvicorn[standard], sqlalchemy[asyncio], asyncpg, alembic, pydantic-settings, passlib[bcrypt], python-jose[cryptography], python-multipart, httpx. Dev deps: pytest, pytest-asyncio, httpx.
|
||||||
|
|
||||||
|
- [x] **A.** Create `frontend/Dockerfile` (multi-stage: Node 20-alpine build stage + nginx:alpine serve stage). Create `frontend/package.json` with dependencies: react, react-dom, react-router-dom, axios, zustand, @tanstack/react-query, i18next, react-i18next, i18next-http-backend, i18next-browser-languagedetector, lucide-react, clsx, tailwind-merge, class-variance-authority. Dev deps: vite, @vitejs/plugin-react, typescript, tailwindcss, postcss, autoprefixer, @types/react, @types/react-dom.
|
||||||
|
|
||||||
|
- [x] **A.** Verify `docker compose build` succeeds for all services and `docker compose up -d` starts postgres, backend, frontend, nginx. Backend health endpoint responds at `/api/v1/health`. Frontend serves through nginx.
|
||||||
|
|
||||||
|
### B. Backend Core Infrastructure (Tasks 7–13)
|
||||||
|
|
||||||
|
- [x] **B.** Create `backend/app/__init__.py`, `backend/app/config.py` using pydantic-settings `BaseSettings`. Fields: `DATABASE_URL`, `SECRET_KEY`, `ACCESS_TOKEN_EXPIRE_MINUTES` (15), `REFRESH_TOKEN_EXPIRE_DAYS` (30), `REFRESH_TOKEN_EXPIRE_HOURS` (24), `CORS_ORIGINS`, `ENVIRONMENT`.
|
||||||
|
|
||||||
|
- [x] **B.** Create `backend/app/database.py`: async engine, `async_sessionmaker`, `get_db` async generator, `Base = declarative_base()` with UUID pk mixin.
|
||||||
|
|
||||||
|
- [x] **B.** Create `backend/app/models/__init__.py`, `backend/app/models/user.py`, `backend/app/models/session.py` matching the schema above. SQLAlchemy 2.0 `mapped_column` style. `updated_at` with `onupdate=func.now()`.
|
||||||
|
|
||||||
|
- [x] **B0.** Set up Alembic: `backend/alembic.ini`, `backend/alembic/env.py` (async-compatible), `backend/alembic/script.py.mako`. Generate initial migration for users + sessions.
|
||||||
|
|
||||||
|
- [x] **B1.** Create `backend/app/main.py`: `create_app()` factory. Lifespan runs Alembic `upgrade head` on startup. CORS middleware. Include API routers. `/api/v1/health` endpoint.
|
||||||
|
|
||||||
|
- [x] **B2.** Create `backend/app/core/__init__.py`, `backend/app/core/security.py`: `hash_password`, `verify_password` (bcrypt), `create_access_token`, `decode_access_token`, `generate_refresh_token`, `hash_refresh_token` (SHA-256).
|
||||||
|
|
||||||
|
- [x] **B3.** Create `backend/app/schemas/__init__.py`, `backend/app/schemas/auth.py`: `RegisterRequest`, `LoginRequest` (with `remember_me`), `RefreshRequest`, `TokenResponse`, `UserResponse`. Create `backend/app/schemas/common.py`: `MessageResponse`.
|
||||||
|
|
||||||
|
### C. Backend Auth Logic (Tasks 14–18)
|
||||||
|
|
||||||
|
- [x] **C4.** Create `backend/app/services/__init__.py`, `backend/app/services/auth_service.py`: `register_user`, `login_user`, `refresh_tokens`, `logout_user`. Each manages session rows. Raises HTTPException on errors.
|
||||||
|
|
||||||
|
- [x] **C5.** Create `backend/app/api/__init__.py`, `backend/app/api/deps.py`: `get_current_user` dependency (JWT → User), `require_admin` dependency.
|
||||||
|
|
||||||
|
- [x] **C6.** Create `backend/app/api/v1/__init__.py`, `backend/app/api/v1/auth.py` router with 5 auth endpoints.
|
||||||
|
|
||||||
|
- [x] **C7.** Create `backend/app/api/v1/router.py` to aggregate v1 sub-routers under `/api/v1`. Include in `main.py`.
|
||||||
|
|
||||||
|
- [x] **C8.** Create `backend/scripts/seed_admin.py`: standalone async script, reads env, creates admin user if not exists. Idempotent.
|
||||||
|
|
||||||
|
### D. Frontend Infrastructure (Tasks 19–27)
|
||||||
|
|
||||||
|
- [x] **D9.** Create `frontend/vite.config.ts` (React plugin, proxy `/api` to backend in dev), `frontend/tsconfig.json`, `frontend/tsconfig.node.json` with `@/` path alias.
|
||||||
|
|
||||||
|
- [x] **D0.** Set up Tailwind CSS: `frontend/tailwind.config.ts`, `frontend/postcss.config.js`, `frontend/src/index.css` (Tailwind directives + shadcn CSS variables for dark mode).
|
||||||
|
|
||||||
|
- [x] **D1.** Initialize shadcn/ui: `frontend/components.json`. Install components: Button, Input, Label, Card, DropdownMenu, Avatar, Sheet, Separator, Sonner. Place in `frontend/src/components/ui/`.
|
||||||
|
|
||||||
|
- [x] **D2.** Set up i18next: `frontend/src/i18n.ts`, `frontend/public/locales/en/translation.json`, `frontend/public/locales/ru/translation.json` with keys for auth, layout, and common strings.
|
||||||
|
|
||||||
|
- [x] **D3.** Create `frontend/src/api/client.ts`: Axios instance, request interceptor (attach token), response interceptor (401 → refresh → retry). Create `frontend/src/api/auth.ts` with typed API functions.
|
||||||
|
|
||||||
|
- [x] **D4.** Create `frontend/src/stores/auth-store.ts` (Zustand, persisted): user, tokens, isAuthenticated, actions. Create `frontend/src/stores/ui-store.ts`: sidebarOpen, theme, persisted.
|
||||||
|
|
||||||
|
- [x] **D5.** Create `frontend/src/components/shared/theme-provider.tsx`, `language-toggle.tsx`, `protected-route.tsx`.
|
||||||
|
|
||||||
|
- [x] **D6.** Create `frontend/src/App.tsx`, `frontend/src/routes.tsx` (React Router v6), `frontend/src/main.tsx` entry point.
|
||||||
|
|
||||||
|
- [x] **D7.** Set up TanStack Query: `frontend/src/lib/query-client.ts`. Wire `QueryClientProvider` in App.
|
||||||
|
|
||||||
|
### E. Frontend Auth Pages & Layout (Tasks 28–33)
|
||||||
|
|
||||||
|
- [x] **E8.** Create `frontend/src/components/auth/login-form.tsx`: email + password + remember me + submit. Calls API, stores tokens, navigates to `/`.
|
||||||
|
|
||||||
|
- [x] **E9.** Create `frontend/src/components/auth/register-form.tsx`: email, username, password, confirm password, full_name. Validation: email format, password min 8, passwords match, username 3-50 chars.
|
||||||
|
|
||||||
|
- [x] **E0.** Create `frontend/src/pages/login.tsx` and `frontend/src/pages/register.tsx`: centered card layout, redirect if authenticated.
|
||||||
|
|
||||||
|
- [x] **E1.** Create `frontend/src/components/layout/app-layout.tsx` (sidebar + main content), `frontend/src/components/layout/sidebar.tsx` (collapsible nav, placeholder items, mobile Sheet drawer).
|
||||||
|
|
||||||
|
- [x] **E2.** Create `frontend/src/components/layout/header.tsx`: sidebar toggle, page title, language toggle, theme toggle, user dropdown with logout.
|
||||||
|
|
||||||
|
- [x] **E3.** Create `frontend/src/pages/dashboard.tsx` (welcome card, placeholder stats), `frontend/src/pages/not-found.tsx` (404).
|
||||||
|
|
||||||
|
### F. Integration & Verification (Tasks 34–36)
|
||||||
|
|
||||||
|
- [x] **F3.** Create `frontend/nginx.conf` for SPA fallback. Ensure multi-stage Dockerfile copies build output and nginx config.
|
||||||
|
|
||||||
|
- [ ] **F35.** End-to-end smoke test: `docker compose up --build`. Verify: postgres + migrations, health endpoint, seed_admin, frontend loads, register, login, dashboard, logout, language toggle, theme toggle.
|
||||||
|
|
||||||
|
- [x] **F3.** Write backend tests: `backend/tests/conftest.py` (async test client), `backend/tests/test_auth.py` (register, login, refresh, logout, invalid credentials, duplicate email, expired token). All pass with `pytest`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files to Create
|
||||||
|
|
||||||
|
### Root
|
||||||
|
|
||||||
|
- `.env.example`
|
||||||
|
- `docker-compose.yml`
|
||||||
|
- `docker-compose.dev.yml`
|
||||||
|
|
||||||
|
### nginx/
|
||||||
|
|
||||||
|
- `nginx/Dockerfile`
|
||||||
|
- `nginx/nginx.conf`
|
||||||
|
|
||||||
|
### backend/
|
||||||
|
|
||||||
|
- `backend/Dockerfile`
|
||||||
|
- `backend/pyproject.toml`
|
||||||
|
- `backend/alembic.ini`
|
||||||
|
- `backend/alembic/env.py`
|
||||||
|
- `backend/alembic/script.py.mako`
|
||||||
|
- `backend/alembic/versions/<initial_migration>.py`
|
||||||
|
- `backend/app/__init__.py`
|
||||||
|
- `backend/app/main.py`
|
||||||
|
- `backend/app/config.py`
|
||||||
|
- `backend/app/database.py`
|
||||||
|
- `backend/app/models/__init__.py`
|
||||||
|
- `backend/app/models/user.py`
|
||||||
|
- `backend/app/models/session.py`
|
||||||
|
- `backend/app/schemas/__init__.py`
|
||||||
|
- `backend/app/schemas/auth.py`
|
||||||
|
- `backend/app/schemas/common.py`
|
||||||
|
- `backend/app/core/__init__.py`
|
||||||
|
- `backend/app/core/security.py`
|
||||||
|
- `backend/app/services/__init__.py`
|
||||||
|
- `backend/app/services/auth_service.py`
|
||||||
|
- `backend/app/api/__init__.py`
|
||||||
|
- `backend/app/api/deps.py`
|
||||||
|
- `backend/app/api/v1/__init__.py`
|
||||||
|
- `backend/app/api/v1/router.py`
|
||||||
|
- `backend/app/api/v1/auth.py`
|
||||||
|
- `backend/scripts/__init__.py`
|
||||||
|
- `backend/scripts/seed_admin.py`
|
||||||
|
- `backend/tests/__init__.py`
|
||||||
|
- `backend/tests/conftest.py`
|
||||||
|
- `backend/tests/test_auth.py`
|
||||||
|
|
||||||
|
### frontend/
|
||||||
|
|
||||||
|
- `frontend/Dockerfile`
|
||||||
|
- `frontend/nginx.conf`
|
||||||
|
- `frontend/package.json`
|
||||||
|
- `frontend/vite.config.ts`
|
||||||
|
- `frontend/tsconfig.json`
|
||||||
|
- `frontend/tsconfig.node.json`
|
||||||
|
- `frontend/tailwind.config.ts`
|
||||||
|
- `frontend/postcss.config.js`
|
||||||
|
- `frontend/components.json`
|
||||||
|
- `frontend/index.html`
|
||||||
|
- `frontend/src/main.tsx`
|
||||||
|
- `frontend/src/App.tsx`
|
||||||
|
- `frontend/src/routes.tsx`
|
||||||
|
- `frontend/src/index.css`
|
||||||
|
- `frontend/src/i18n.ts`
|
||||||
|
- `frontend/src/vite-env.d.ts`
|
||||||
|
- `frontend/src/lib/query-client.ts`
|
||||||
|
- `frontend/src/lib/utils.ts`
|
||||||
|
- `frontend/src/api/client.ts`
|
||||||
|
- `frontend/src/api/auth.ts`
|
||||||
|
- `frontend/src/stores/auth-store.ts`
|
||||||
|
- `frontend/src/stores/ui-store.ts`
|
||||||
|
- `frontend/src/components/ui/` (shadcn components)
|
||||||
|
- `frontend/src/components/shared/theme-provider.tsx`
|
||||||
|
- `frontend/src/components/shared/language-toggle.tsx`
|
||||||
|
- `frontend/src/components/shared/protected-route.tsx`
|
||||||
|
- `frontend/src/components/auth/login-form.tsx`
|
||||||
|
- `frontend/src/components/auth/register-form.tsx`
|
||||||
|
- `frontend/src/components/layout/app-layout.tsx`
|
||||||
|
- `frontend/src/components/layout/sidebar.tsx`
|
||||||
|
- `frontend/src/components/layout/header.tsx`
|
||||||
|
- `frontend/src/pages/login.tsx`
|
||||||
|
- `frontend/src/pages/register.tsx`
|
||||||
|
- `frontend/src/pages/dashboard.tsx`
|
||||||
|
- `frontend/src/pages/not-found.tsx`
|
||||||
|
- `frontend/public/locales/en/translation.json`
|
||||||
|
- `frontend/public/locales/ru/translation.json`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
1. `docker compose up --build` starts all 4 services (postgres, backend, frontend, nginx) without errors
|
||||||
|
2. `GET /api/v1/health` returns `{"status": "ok"}`
|
||||||
|
3. Alembic migration creates `users` and `sessions` tables with correct schema
|
||||||
|
4. `seed_admin.py` creates an admin user; re-running is idempotent
|
||||||
|
5. `POST /api/v1/auth/register` creates a new user and returns tokens
|
||||||
|
6. `POST /api/v1/auth/login` with valid credentials returns tokens; `remember_me=true` → 30-day refresh, `false` → 24-hour
|
||||||
|
7. `POST /api/v1/auth/refresh` rotates refresh token and returns new pair
|
||||||
|
8. `POST /api/v1/auth/logout` invalidates the session
|
||||||
|
9. `GET /api/v1/auth/me` with valid token returns user data; expired/invalid → 401
|
||||||
|
10. Frontend loads at `http://localhost`, unauthenticated users see login page
|
||||||
|
11. User can register, log in, and see dashboard with their name
|
||||||
|
12. Sidebar renders with placeholder navigation; header has theme toggle, language toggle, user menu with logout
|
||||||
|
13. Dark/light theme toggle works (persisted across reload)
|
||||||
|
14. Language toggle switches between English and Russian (persisted across reload)
|
||||||
|
15. Axios interceptor auto-refreshes access token on 401 and retries the request
|
||||||
|
16. All backend auth tests pass (`pytest`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
**IN PROGRESS** — All code written. F35 (Docker smoke test) blocked: Docker not installed on this machine. Install Docker Desktop to complete end-to-end verification.
|
||||||
Reference in New Issue
Block a user