Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 05309f26b4 | |||
| 3ee4ed7e7f | |||
| ce8393a8e2 | |||
| 78b503fe43 | |||
| 48a7ed68e6 |
@@ -0,0 +1,13 @@
|
|||||||
|
# Copy this file to .env and fill in the values
|
||||||
|
|
||||||
|
# openrouter.ai API key
|
||||||
|
OPENROUTER_API_KEY=
|
||||||
|
|
||||||
|
# JWT secret for signing tokens (generate with: python -c "import secrets; print(secrets.token_hex(32))")
|
||||||
|
JWT_SECRET=
|
||||||
|
|
||||||
|
# Path to DuckDB database file
|
||||||
|
DB_PATH=data/app.db
|
||||||
|
|
||||||
|
# Log level (DEBUG, INFO, WARNING, ERROR)
|
||||||
|
LOG_LEVEL=INFO
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""DuckDB singleton connection with asyncio write lock and schema migrations."""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import duckdb
|
||||||
|
|
||||||
|
_conn: duckdb.DuckDBPyConnection | None = None
|
||||||
|
_write_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_path() -> str:
|
||||||
|
return os.getenv("DB_PATH", "data/app.db")
|
||||||
|
|
||||||
|
|
||||||
|
def init_db(path: str | None = None) -> duckdb.DuckDBPyConnection:
|
||||||
|
"""Open (or reuse) the DuckDB connection and run schema migrations."""
|
||||||
|
global _conn
|
||||||
|
if _conn is not None:
|
||||||
|
return _conn
|
||||||
|
db_path = path or get_db_path()
|
||||||
|
if db_path != ":memory:":
|
||||||
|
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
||||||
|
_conn = duckdb.connect(db_path)
|
||||||
|
_run_migrations(_conn)
|
||||||
|
return _conn
|
||||||
|
|
||||||
|
|
||||||
|
def get_conn() -> duckdb.DuckDBPyConnection:
|
||||||
|
"""Return the active connection; raises if not yet initialised."""
|
||||||
|
if _conn is None:
|
||||||
|
raise RuntimeError("Database not initialised. Call init_db() first.")
|
||||||
|
return _conn
|
||||||
|
|
||||||
|
|
||||||
|
def close_db() -> None:
|
||||||
|
"""Close the connection (called on app shutdown)."""
|
||||||
|
global _conn
|
||||||
|
if _conn is not None:
|
||||||
|
_conn.close()
|
||||||
|
_conn = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_write_lock() -> asyncio.Lock:
|
||||||
|
"""Return the asyncio lock that serialises write operations."""
|
||||||
|
return _write_lock
|
||||||
|
|
||||||
|
|
||||||
|
def _run_migrations(conn: duckdb.DuckDBPyConnection) -> None:
|
||||||
|
conn.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID DEFAULT uuid() PRIMARY KEY,
|
||||||
|
email VARCHAR NOT NULL UNIQUE,
|
||||||
|
password_hash VARCHAR NOT NULL,
|
||||||
|
role VARCHAR DEFAULT 'user',
|
||||||
|
created_at TIMESTAMP DEFAULT now(),
|
||||||
|
updated_at TIMESTAMP DEFAULT now()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
conn.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||||
|
jti UUID DEFAULT uuid() PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL,
|
||||||
|
issued_at TIMESTAMP DEFAULT now(),
|
||||||
|
expires_at TIMESTAMP NOT NULL,
|
||||||
|
revoked BOOLEAN DEFAULT false
|
||||||
|
)
|
||||||
|
""")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""FastAPI dependencies (e.g. authenticated user extraction)."""
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from jose import JWTError
|
||||||
|
|
||||||
|
from backend.app.services.auth import decode_token
|
||||||
|
|
||||||
|
_bearer = HTTPBearer()
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(
|
||||||
|
credentials: HTTPAuthorizationCredentials = Depends(_bearer),
|
||||||
|
) -> dict:
|
||||||
|
"""Extract and validate the Bearer JWT. Returns the token payload."""
|
||||||
|
credentials_error = HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Could not validate credentials.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
payload = decode_token(credentials.credentials)
|
||||||
|
except JWTError:
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
if payload.get("type") != "access":
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
user_id: str | None = payload.get("sub")
|
||||||
|
if user_id is None:
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
return {"id": user_id, "email": payload.get("email"), "role": payload.get("role")}
|
||||||
|
|
||||||
|
|
||||||
|
async def require_admin(current_user: dict = Depends(get_current_user)) -> dict:
|
||||||
|
"""Raise 403 if the authenticated user is not an admin."""
|
||||||
|
if current_user.get("role") != "admin":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Admin access required.",
|
||||||
|
)
|
||||||
|
return current_user
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
from backend.app.routers import auth as auth_router
|
||||||
|
from backend.app.routers import users as users_router
|
||||||
|
from backend.app.routers import admin as admin_router
|
||||||
|
from backend.app.routers import ai as ai_router
|
||||||
|
from backend.app.routers import generate as generate_router
|
||||||
|
from backend.app.db import close_db, init_db
|
||||||
|
import os
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
init_db()
|
||||||
|
yield
|
||||||
|
close_db()
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="AI Allucanget Biz API",
|
||||||
|
description="Multi-modal AI generation API powered by openrouter.ai",
|
||||||
|
version="0.1.0",
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=[os.getenv("CORS_ORIGINS", "http://localhost:5000")],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(auth_router.router)
|
||||||
|
app.include_router(users_router.router)
|
||||||
|
app.include_router(admin_router.router)
|
||||||
|
app.include_router(ai_router.router)
|
||||||
|
app.include_router(generate_router.router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health", tags=["health"])
|
||||||
|
async def health() -> dict:
|
||||||
|
return {"status": "ok"}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""Pydantic schemas for AI generation endpoints."""
|
||||||
|
from typing import Any
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class ChatMessage(BaseModel):
|
||||||
|
role: str # "user" | "assistant" | "system"
|
||||||
|
content: str
|
||||||
|
|
||||||
|
|
||||||
|
class ChatRequest(BaseModel):
|
||||||
|
model: str
|
||||||
|
messages: list[ChatMessage]
|
||||||
|
temperature: float = 0.7
|
||||||
|
max_tokens: int = 1024
|
||||||
|
|
||||||
|
|
||||||
|
class ChatResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
model: str
|
||||||
|
content: str
|
||||||
|
usage: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ModelInfo(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
context_length: int | None = None
|
||||||
|
pricing: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- Text generation ---
|
||||||
|
|
||||||
|
class TextRequest(BaseModel):
|
||||||
|
model: str
|
||||||
|
prompt: str
|
||||||
|
system_prompt: str | None = None
|
||||||
|
temperature: float = 0.7
|
||||||
|
max_tokens: int = 1024
|
||||||
|
|
||||||
|
|
||||||
|
class TextResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
model: str
|
||||||
|
content: str
|
||||||
|
usage: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- Image generation ---
|
||||||
|
|
||||||
|
class ImageRequest(BaseModel):
|
||||||
|
model: str
|
||||||
|
prompt: str
|
||||||
|
n: int = 1
|
||||||
|
size: str = "1024x1024"
|
||||||
|
|
||||||
|
|
||||||
|
class ImageResult(BaseModel):
|
||||||
|
url: str | None = None
|
||||||
|
b64_json: str | None = None
|
||||||
|
revised_prompt: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ImageResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
model: str
|
||||||
|
images: list[ImageResult]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Video generation ---
|
||||||
|
|
||||||
|
class VideoRequest(BaseModel):
|
||||||
|
model: str
|
||||||
|
prompt: str
|
||||||
|
duration_seconds: int | None = None
|
||||||
|
aspect_ratio: str = "16:9"
|
||||||
|
|
||||||
|
|
||||||
|
class VideoFromImageRequest(BaseModel):
|
||||||
|
model: str
|
||||||
|
image_url: str
|
||||||
|
prompt: str
|
||||||
|
duration_seconds: int | None = None
|
||||||
|
aspect_ratio: str = "16:9"
|
||||||
|
|
||||||
|
|
||||||
|
class VideoResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
model: str
|
||||||
|
status: str # "queued" | "processing" | "completed"
|
||||||
|
video_url: str | None = None
|
||||||
|
metadata: dict[str, Any] | None = None
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""Pydantic schemas for authentication endpoints."""
|
||||||
|
from pydantic import BaseModel, EmailStr
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
class TokenResponse(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
refresh_token: str
|
||||||
|
token_type: str = "bearer"
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshRequest(BaseModel):
|
||||||
|
refresh_token: str
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Pydantic schemas for user management endpoints."""
|
||||||
|
from pydantic import BaseModel, EmailStr
|
||||||
|
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
email: str
|
||||||
|
role: str
|
||||||
|
|
||||||
|
|
||||||
|
class UpdateUserRequest(BaseModel):
|
||||||
|
email: EmailStr | None = None
|
||||||
|
password: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SetRoleRequest(BaseModel):
|
||||||
|
role: str
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Admin router: operational endpoints for application management."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from backend.app.db import get_conn, get_write_lock
|
||||||
|
from backend.app.dependencies import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
async def get_stats(_: dict = Depends(require_admin)) -> dict:
|
||||||
|
"""Return aggregate statistics: user counts and token counts."""
|
||||||
|
conn = get_conn()
|
||||||
|
total_users = conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]
|
||||||
|
users_by_role = conn.execute(
|
||||||
|
"SELECT role, COUNT(*) FROM users GROUP BY role ORDER BY role"
|
||||||
|
).fetchall()
|
||||||
|
total_tokens = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM refresh_tokens").fetchone()[0]
|
||||||
|
active_tokens = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM refresh_tokens WHERE revoked = false AND expires_at > ?",
|
||||||
|
[datetime.now(timezone.utc)],
|
||||||
|
).fetchone()[0]
|
||||||
|
return {
|
||||||
|
"users": {
|
||||||
|
"total": total_users,
|
||||||
|
"by_role": {row[0]: row[1] for row in users_by_role},
|
||||||
|
},
|
||||||
|
"refresh_tokens": {
|
||||||
|
"total": total_tokens,
|
||||||
|
"active": active_tokens,
|
||||||
|
"revoked_or_expired": total_tokens - active_tokens,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/db")
|
||||||
|
async def db_health(_: dict = Depends(require_admin)) -> dict:
|
||||||
|
"""Verify DuckDB is reachable."""
|
||||||
|
conn = get_conn()
|
||||||
|
result = conn.execute("SELECT 1").fetchone()[0]
|
||||||
|
return {"status": "ok" if result == 1 else "error"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tokens/purge", status_code=200)
|
||||||
|
async def purge_tokens(_: dict = Depends(require_admin)) -> dict:
|
||||||
|
"""Delete all expired or revoked refresh tokens. Returns count removed."""
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
async with lock:
|
||||||
|
before = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM refresh_tokens").fetchone()[0]
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM refresh_tokens WHERE revoked = true OR expires_at <= ?", [
|
||||||
|
now]
|
||||||
|
)
|
||||||
|
after = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM refresh_tokens").fetchone()[0]
|
||||||
|
return {"deleted": before - after, "remaining": after}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""AI router: model listing and chat completions via OpenRouter."""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
|
||||||
|
from backend.app.dependencies import get_current_user
|
||||||
|
from backend.app.models.ai import ChatRequest, ChatResponse, ModelInfo
|
||||||
|
from backend.app.services import openrouter
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/ai", tags=["ai"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/models", response_model=list[ModelInfo])
|
||||||
|
async def get_models(_: dict = Depends(get_current_user)) -> list[ModelInfo]:
|
||||||
|
"""List available AI models from OpenRouter."""
|
||||||
|
try:
|
||||||
|
raw = await openrouter.list_models()
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
|
detail=f"OpenRouter error: {exc}",
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
ModelInfo(
|
||||||
|
id=m.get("id", ""),
|
||||||
|
name=m.get("name", m.get("id", "")),
|
||||||
|
context_length=m.get("context_length"),
|
||||||
|
pricing=m.get("pricing"),
|
||||||
|
)
|
||||||
|
for m in raw
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/chat", response_model=ChatResponse)
|
||||||
|
async def chat(
|
||||||
|
body: ChatRequest,
|
||||||
|
_: dict = Depends(get_current_user),
|
||||||
|
) -> ChatResponse:
|
||||||
|
"""Send a chat completion request through OpenRouter."""
|
||||||
|
try:
|
||||||
|
result = await openrouter.chat_completion(
|
||||||
|
model=body.model,
|
||||||
|
messages=[m.model_dump() for m in body.messages],
|
||||||
|
temperature=body.temperature,
|
||||||
|
max_tokens=body.max_tokens,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
|
detail=f"OpenRouter error: {exc}",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
choice = result["choices"][0]
|
||||||
|
return ChatResponse(
|
||||||
|
id=result["id"],
|
||||||
|
model=result.get("model", body.model),
|
||||||
|
content=choice["message"]["content"],
|
||||||
|
usage=result.get("usage"),
|
||||||
|
)
|
||||||
|
except (KeyError, IndexError) as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
|
detail=f"Unexpected response format from OpenRouter: {exc}",
|
||||||
|
)
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"""Auth router: register, login, refresh, logout."""
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
from jose import JWTError
|
||||||
|
|
||||||
|
from backend.app.models.auth import LoginRequest, RefreshRequest, RegisterRequest, TokenResponse
|
||||||
|
from backend.app.services.auth import (
|
||||||
|
authenticate_user,
|
||||||
|
create_access_token,
|
||||||
|
create_refresh_token,
|
||||||
|
decode_token,
|
||||||
|
register_user,
|
||||||
|
revoke_refresh_token,
|
||||||
|
store_refresh_token,
|
||||||
|
validate_refresh_token_jti,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def register(body: RegisterRequest) -> dict:
|
||||||
|
try:
|
||||||
|
user = await register_user(body.email, body.password)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
|
||||||
|
return {"id": user["id"], "email": user["email"], "role": user["role"]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login", response_model=TokenResponse)
|
||||||
|
async def login(body: LoginRequest) -> TokenResponse:
|
||||||
|
user = await authenticate_user(body.email, body.password)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid credentials.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
jti = str(uuid.uuid4())
|
||||||
|
await store_refresh_token(user["id"], jti)
|
||||||
|
return TokenResponse(
|
||||||
|
access_token=create_access_token(user["id"], user["email"], user["role"]),
|
||||||
|
refresh_token=create_refresh_token(user["id"], jti),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/refresh", response_model=TokenResponse)
|
||||||
|
async def refresh(body: RefreshRequest) -> TokenResponse:
|
||||||
|
credentials_error = HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or expired refresh token.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
payload = decode_token(body.refresh_token)
|
||||||
|
except JWTError:
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
if payload.get("type") != "refresh":
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
user_id: str = payload.get("sub", "")
|
||||||
|
jti: str = payload.get("jti", "")
|
||||||
|
|
||||||
|
if not await validate_refresh_token_jti(jti, user_id):
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
# Rotate: revoke old JTI, issue new pair
|
||||||
|
await revoke_refresh_token(jti)
|
||||||
|
new_jti = str(uuid.uuid4())
|
||||||
|
await store_refresh_token(user_id, new_jti)
|
||||||
|
|
||||||
|
from backend.app.db import get_conn
|
||||||
|
conn = get_conn()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT email, role FROM users WHERE id = ?", [user_id]
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise credentials_error
|
||||||
|
|
||||||
|
return TokenResponse(
|
||||||
|
access_token=create_access_token(user_id, row[0], row[1]),
|
||||||
|
refresh_token=create_refresh_token(user_id, new_jti),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def logout(body: RefreshRequest) -> None:
|
||||||
|
try:
|
||||||
|
payload = decode_token(body.refresh_token)
|
||||||
|
except JWTError:
|
||||||
|
return # Already invalid — treat as success
|
||||||
|
jti = payload.get("jti", "")
|
||||||
|
if jti:
|
||||||
|
await revoke_refresh_token(jti)
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""Generate router: text, image, video, and image-to-video generation."""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
|
||||||
|
from backend.app.dependencies import get_current_user
|
||||||
|
from backend.app.models.ai import (
|
||||||
|
ImageRequest,
|
||||||
|
ImageResponse,
|
||||||
|
ImageResult,
|
||||||
|
TextRequest,
|
||||||
|
TextResponse,
|
||||||
|
VideoFromImageRequest,
|
||||||
|
VideoRequest,
|
||||||
|
VideoResponse,
|
||||||
|
)
|
||||||
|
from backend.app.services import openrouter
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/generate", tags=["generate"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/text", response_model=TextResponse)
|
||||||
|
async def generate_text(
|
||||||
|
body: TextRequest,
|
||||||
|
_: dict = Depends(get_current_user),
|
||||||
|
) -> TextResponse:
|
||||||
|
"""Generate text from a prompt using a chat model."""
|
||||||
|
messages = []
|
||||||
|
if body.system_prompt:
|
||||||
|
messages.append({"role": "system", "content": body.system_prompt})
|
||||||
|
messages.append({"role": "user", "content": body.prompt})
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await openrouter.chat_completion(
|
||||||
|
model=body.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=body.temperature,
|
||||||
|
max_tokens=body.max_tokens,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY, detail=f"OpenRouter error: {exc}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
choice = result["choices"][0]
|
||||||
|
return TextResponse(
|
||||||
|
id=result["id"],
|
||||||
|
model=result.get("model", body.model),
|
||||||
|
content=choice["message"]["content"],
|
||||||
|
usage=result.get("usage"),
|
||||||
|
)
|
||||||
|
except (KeyError, IndexError) as exc:
|
||||||
|
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
|
detail=f"Unexpected response format: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/image", response_model=ImageResponse)
|
||||||
|
async def generate_image(
|
||||||
|
body: ImageRequest,
|
||||||
|
_: dict = Depends(get_current_user),
|
||||||
|
) -> ImageResponse:
|
||||||
|
"""Generate images from a text prompt."""
|
||||||
|
try:
|
||||||
|
result = await openrouter.generate_image(
|
||||||
|
model=body.model,
|
||||||
|
prompt=body.prompt,
|
||||||
|
n=body.n,
|
||||||
|
size=body.size,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY, detail=f"OpenRouter error: {exc}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
images = [
|
||||||
|
ImageResult(
|
||||||
|
url=item.get("url"),
|
||||||
|
b64_json=item.get("b64_json"),
|
||||||
|
revised_prompt=item.get("revised_prompt"),
|
||||||
|
)
|
||||||
|
for item in result.get("data", [])
|
||||||
|
]
|
||||||
|
return ImageResponse(
|
||||||
|
id=result.get("id", ""),
|
||||||
|
model=result.get("model", body.model),
|
||||||
|
images=images,
|
||||||
|
)
|
||||||
|
except (KeyError, TypeError) as exc:
|
||||||
|
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY,
|
||||||
|
detail=f"Unexpected response format: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/video", response_model=VideoResponse)
|
||||||
|
async def generate_video(
|
||||||
|
body: VideoRequest,
|
||||||
|
_: dict = Depends(get_current_user),
|
||||||
|
) -> VideoResponse:
|
||||||
|
"""Generate a video from a text prompt."""
|
||||||
|
try:
|
||||||
|
result = await openrouter.generate_video(
|
||||||
|
model=body.model,
|
||||||
|
prompt=body.prompt,
|
||||||
|
duration_seconds=body.duration_seconds,
|
||||||
|
aspect_ratio=body.aspect_ratio,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY, detail=f"OpenRouter error: {exc}")
|
||||||
|
|
||||||
|
return VideoResponse(
|
||||||
|
id=result.get("id", ""),
|
||||||
|
model=result.get("model", body.model),
|
||||||
|
status=result.get("status", "queued"),
|
||||||
|
video_url=result.get("video_url"),
|
||||||
|
metadata=result.get("metadata"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/video/from-image", response_model=VideoResponse)
|
||||||
|
async def generate_video_from_image(
|
||||||
|
body: VideoFromImageRequest,
|
||||||
|
_: dict = Depends(get_current_user),
|
||||||
|
) -> VideoResponse:
|
||||||
|
"""Generate a video from an image and a text prompt."""
|
||||||
|
try:
|
||||||
|
result = await openrouter.generate_video_from_image(
|
||||||
|
model=body.model,
|
||||||
|
image_url=body.image_url,
|
||||||
|
prompt=body.prompt,
|
||||||
|
duration_seconds=body.duration_seconds,
|
||||||
|
aspect_ratio=body.aspect_ratio,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_502_BAD_GATEWAY, detail=f"OpenRouter error: {exc}")
|
||||||
|
|
||||||
|
return VideoResponse(
|
||||||
|
id=result.get("id", ""),
|
||||||
|
model=result.get("model", body.model),
|
||||||
|
status=result.get("status", "queued"),
|
||||||
|
video_url=result.get("video_url"),
|
||||||
|
metadata=result.get("metadata"),
|
||||||
|
)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Users router: self-service profile and admin user management."""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
|
||||||
|
from backend.app.dependencies import get_current_user, require_admin
|
||||||
|
from backend.app.models.users import SetRoleRequest, UpdateUserRequest, UserResponse
|
||||||
|
from backend.app.services.users import (
|
||||||
|
delete_user,
|
||||||
|
get_user,
|
||||||
|
list_users,
|
||||||
|
set_user_role,
|
||||||
|
update_user,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/users", tags=["users"])
|
||||||
|
|
||||||
|
ALLOWED_ROLES = {"user", "admin"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Self-service
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserResponse)
|
||||||
|
async def get_me(current_user: dict = Depends(get_current_user)) -> UserResponse:
|
||||||
|
user = await get_user(current_user["id"])
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||||
|
return UserResponse(**user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/me", response_model=UserResponse)
|
||||||
|
async def update_me(
|
||||||
|
body: UpdateUserRequest,
|
||||||
|
current_user: dict = Depends(get_current_user),
|
||||||
|
) -> UserResponse:
|
||||||
|
try:
|
||||||
|
user = await update_user(current_user["id"], email=body.email, password=body.password)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT, detail=str(exc))
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||||
|
return UserResponse(**user)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Admin
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@router.get("", response_model=list[UserResponse])
|
||||||
|
async def get_all_users(_: dict = Depends(require_admin)) -> list[UserResponse]:
|
||||||
|
users = await list_users()
|
||||||
|
return [UserResponse(**u) for u in users]
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def remove_user(
|
||||||
|
user_id: str,
|
||||||
|
current_user: dict = Depends(require_admin),
|
||||||
|
) -> None:
|
||||||
|
if user_id == current_user["id"]:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot delete your own account.",
|
||||||
|
)
|
||||||
|
await delete_user(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}/role", response_model=UserResponse)
|
||||||
|
async def change_role(
|
||||||
|
user_id: str,
|
||||||
|
body: SetRoleRequest,
|
||||||
|
_: dict = Depends(require_admin),
|
||||||
|
) -> UserResponse:
|
||||||
|
if body.role not in ALLOWED_ROLES:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail=f"Role must be one of: {', '.join(sorted(ALLOWED_ROLES))}.",
|
||||||
|
)
|
||||||
|
user = await set_user_role(user_id, body.role)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||||
|
return UserResponse(**user)
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""Authentication service: password hashing, JWT creation/verification, token management."""
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
from backend.app.db import get_conn, get_write_lock
|
||||||
|
|
||||||
|
_pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES = 15
|
||||||
|
REFRESH_TOKEN_EXPIRE_DAYS = 7
|
||||||
|
ALGORITHM = "HS256"
|
||||||
|
|
||||||
|
|
||||||
|
def _secret() -> str:
|
||||||
|
secret = os.getenv("JWT_SECRET")
|
||||||
|
if not secret:
|
||||||
|
raise RuntimeError("JWT_SECRET environment variable is not set.")
|
||||||
|
return secret
|
||||||
|
|
||||||
|
|
||||||
|
# --- Password ---
|
||||||
|
|
||||||
|
def hash_password(plain: str) -> str:
|
||||||
|
return _pwd_context.hash(plain)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
|
return _pwd_context.verify(plain, hashed)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Tokens ---
|
||||||
|
|
||||||
|
def create_access_token(user_id: str, email: str, role: str) -> str:
|
||||||
|
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
payload = {
|
||||||
|
"sub": user_id,
|
||||||
|
"email": email,
|
||||||
|
"role": role,
|
||||||
|
"exp": expire,
|
||||||
|
"type": "access",
|
||||||
|
}
|
||||||
|
return jwt.encode(payload, _secret(), algorithm=ALGORITHM)
|
||||||
|
|
||||||
|
|
||||||
|
def create_refresh_token(user_id: str, jti: str) -> str:
|
||||||
|
expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
|
||||||
|
payload = {
|
||||||
|
"sub": user_id,
|
||||||
|
"jti": jti,
|
||||||
|
"exp": expire,
|
||||||
|
"type": "refresh",
|
||||||
|
}
|
||||||
|
return jwt.encode(payload, _secret(), algorithm=ALGORITHM)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_token(token: str) -> dict[str, Any]:
|
||||||
|
"""Decode and validate a JWT. Raises JWTError on failure."""
|
||||||
|
return jwt.decode(token, _secret(), algorithms=[ALGORITHM])
|
||||||
|
|
||||||
|
|
||||||
|
# --- Database operations ---
|
||||||
|
|
||||||
|
async def register_user(email: str, password: str) -> dict[str, Any]:
|
||||||
|
"""Insert a new user. Returns the created user row."""
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
async with lock:
|
||||||
|
existing = conn.execute(
|
||||||
|
"SELECT id FROM users WHERE email = ?", [email]
|
||||||
|
).fetchone()
|
||||||
|
if existing:
|
||||||
|
raise ValueError("Email already registered.")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO users (email, password_hash) VALUES (?, ?)",
|
||||||
|
[email, hash_password(password)],
|
||||||
|
)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email, role FROM users WHERE email = ?", [email]
|
||||||
|
).fetchone()
|
||||||
|
return {"id": str(row[0]), "email": row[1], "role": row[2]}
|
||||||
|
|
||||||
|
|
||||||
|
async def authenticate_user(email: str, password: str) -> dict[str, Any] | None:
|
||||||
|
"""Return user dict if credentials are valid, else None."""
|
||||||
|
conn = get_conn()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email, password_hash, role FROM users WHERE email = ?", [email]
|
||||||
|
).fetchone()
|
||||||
|
if row is None or not verify_password(password, row[2]):
|
||||||
|
return None
|
||||||
|
return {"id": str(row[0]), "email": row[1], "role": row[3]}
|
||||||
|
|
||||||
|
|
||||||
|
async def store_refresh_token(user_id: str, jti: str) -> None:
|
||||||
|
"""Persist a refresh token JTI in the database."""
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
from datetime import timedelta
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
|
||||||
|
async with lock:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO refresh_tokens (jti, user_id, expires_at) VALUES (?, ?, ?)",
|
||||||
|
[jti, user_id, expires_at],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def revoke_refresh_token(jti: str) -> None:
|
||||||
|
"""Mark a refresh token as revoked."""
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
async with lock:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE refresh_tokens SET revoked = true WHERE jti = ?", [jti]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def validate_refresh_token_jti(jti: str, user_id: str) -> bool:
|
||||||
|
"""Return True if the JTI exists, is not revoked, and belongs to user_id."""
|
||||||
|
conn = get_conn()
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM refresh_tokens
|
||||||
|
WHERE jti = ? AND user_id = ? AND revoked = false AND expires_at > ?
|
||||||
|
""",
|
||||||
|
[jti, user_id, now],
|
||||||
|
).fetchone()
|
||||||
|
return row is not None
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""OpenRouter API client (OpenAI-compatible interface)."""
|
||||||
|
import os
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
|
||||||
|
|
||||||
|
|
||||||
|
def _api_key() -> str:
|
||||||
|
key = os.getenv("OPENROUTER_API_KEY")
|
||||||
|
if not key:
|
||||||
|
raise RuntimeError(
|
||||||
|
"OPENROUTER_API_KEY environment variable is not set.")
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def _headers() -> dict[str, str]:
|
||||||
|
return {
|
||||||
|
"Authorization": f"Bearer {_api_key()}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"HTTP-Referer": os.getenv("APP_URL", "https://ai.allucanget.biz"),
|
||||||
|
"X-Title": os.getenv("APP_NAME", "AI Allucanget"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def list_models() -> list[dict[str, Any]]:
|
||||||
|
"""Return available models from OpenRouter."""
|
||||||
|
base_url = os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL)
|
||||||
|
async with httpx.AsyncClient(timeout=15) as client:
|
||||||
|
resp = client.build_request(
|
||||||
|
"GET", f"{base_url}/models", headers=_headers())
|
||||||
|
response = await client.send(resp)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json().get("data", [])
|
||||||
|
|
||||||
|
|
||||||
|
async def chat_completion(
|
||||||
|
model: str,
|
||||||
|
messages: list[dict[str, str]],
|
||||||
|
temperature: float = 0.7,
|
||||||
|
max_tokens: int = 1024,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Send a chat completion request to OpenRouter."""
|
||||||
|
base_url = os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL)
|
||||||
|
payload = {
|
||||||
|
"model": model,
|
||||||
|
"messages": messages,
|
||||||
|
"temperature": temperature,
|
||||||
|
"max_tokens": max_tokens,
|
||||||
|
}
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
response = await client.send(resp)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_image(
|
||||||
|
model: str,
|
||||||
|
prompt: str,
|
||||||
|
n: int = 1,
|
||||||
|
size: str = "1024x1024",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Request image generation via OpenRouter /images/generations."""
|
||||||
|
base_url = os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL)
|
||||||
|
payload = {"model": model, "prompt": prompt, "n": n, "size": size}
|
||||||
|
async with httpx.AsyncClient(timeout=120) as client:
|
||||||
|
resp = client.build_request(
|
||||||
|
"POST", f"{base_url}/images/generations", headers=_headers(), json=payload
|
||||||
|
)
|
||||||
|
response = await client.send(resp)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_video(
|
||||||
|
model: str,
|
||||||
|
prompt: str,
|
||||||
|
duration_seconds: int | None = None,
|
||||||
|
aspect_ratio: str = "16:9",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Request text-to-video generation via OpenRouter."""
|
||||||
|
base_url = os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL)
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"model": model,
|
||||||
|
"prompt": prompt,
|
||||||
|
"aspect_ratio": aspect_ratio,
|
||||||
|
}
|
||||||
|
if duration_seconds is not None:
|
||||||
|
payload["duration_seconds"] = duration_seconds
|
||||||
|
async with httpx.AsyncClient(timeout=120) as client:
|
||||||
|
resp = client.build_request(
|
||||||
|
"POST", f"{base_url}/video/generations", headers=_headers(), json=payload
|
||||||
|
)
|
||||||
|
response = await client.send(resp)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_video_from_image(
|
||||||
|
model: str,
|
||||||
|
image_url: str,
|
||||||
|
prompt: str,
|
||||||
|
duration_seconds: int | None = None,
|
||||||
|
aspect_ratio: str = "16:9",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Request image-to-video generation via OpenRouter."""
|
||||||
|
base_url = os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL)
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"model": model,
|
||||||
|
"image_url": image_url,
|
||||||
|
"prompt": prompt,
|
||||||
|
"aspect_ratio": aspect_ratio,
|
||||||
|
}
|
||||||
|
if duration_seconds is not None:
|
||||||
|
payload["duration_seconds"] = duration_seconds
|
||||||
|
async with httpx.AsyncClient(timeout=120) as client:
|
||||||
|
resp = client.build_request(
|
||||||
|
"POST", f"{base_url}/video/generations/from-image", headers=_headers(), json=payload
|
||||||
|
)
|
||||||
|
response = await client.send(resp)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""User management service: CRUD helpers against DuckDB."""
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from backend.app.db import get_conn, get_write_lock
|
||||||
|
from backend.app.services.auth import hash_password
|
||||||
|
|
||||||
|
|
||||||
|
async def get_user(user_id: str) -> dict[str, Any] | None:
|
||||||
|
conn = get_conn()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email, role FROM users WHERE id = ?", [user_id]
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return {"id": str(row[0]), "email": row[1], "role": row[2]}
|
||||||
|
|
||||||
|
|
||||||
|
async def list_users() -> list[dict[str, Any]]:
|
||||||
|
conn = get_conn()
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id, email, role FROM users ORDER BY email").fetchall()
|
||||||
|
return [{"id": str(r[0]), "email": r[1], "role": r[2]} for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
async def update_user(
|
||||||
|
user_id: str,
|
||||||
|
email: str | None = None,
|
||||||
|
password: str | None = None,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
"""Update email and/or password. Returns updated user or None if not found."""
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
|
||||||
|
if email is None and password is None:
|
||||||
|
return await get_user(user_id)
|
||||||
|
|
||||||
|
async with lock:
|
||||||
|
if email is not None:
|
||||||
|
existing = conn.execute(
|
||||||
|
"SELECT id FROM users WHERE email = ? AND id != ?", [
|
||||||
|
email, user_id]
|
||||||
|
).fetchone()
|
||||||
|
if existing:
|
||||||
|
raise ValueError("Email already in use.")
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE users SET email = ?, updated_at = now() WHERE id = ?",
|
||||||
|
[email, user_id],
|
||||||
|
)
|
||||||
|
if password is not None:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE users SET password_hash = ?, updated_at = now() WHERE id = ?",
|
||||||
|
[hash_password(password), user_id],
|
||||||
|
)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email, role FROM users WHERE id = ?", [user_id]
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return {"id": str(row[0]), "email": row[1], "role": row[2]}
|
||||||
|
|
||||||
|
|
||||||
|
async def set_user_role(user_id: str, role: str) -> dict[str, Any] | None:
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
async with lock:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE users SET role = ?, updated_at = now() WHERE id = ?",
|
||||||
|
[role, user_id],
|
||||||
|
)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id, email, role FROM users WHERE id = ?", [user_id]
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return {"id": str(row[0]), "email": row[1], "role": row[2]}
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_user(user_id: str) -> bool:
|
||||||
|
"""Delete user and their refresh tokens. Returns True if a row was removed."""
|
||||||
|
conn = get_conn()
|
||||||
|
lock = get_write_lock()
|
||||||
|
async with lock:
|
||||||
|
conn.execute("DELETE FROM refresh_tokens WHERE user_id = ?", [user_id])
|
||||||
|
conn.execute("DELETE FROM users WHERE id = ?", [user_id])
|
||||||
|
return True
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"""Integration tests for admin endpoints."""
|
||||||
|
import os
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from httpx import AsyncClient, ASGITransport
|
||||||
|
|
||||||
|
from backend.app.main import app
|
||||||
|
from backend.app import db as db_module
|
||||||
|
|
||||||
|
os.environ.setdefault("JWT_SECRET", "test-secret-key-for-testing-only")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fresh_db():
|
||||||
|
db_module._conn = None
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
yield
|
||||||
|
db_module.close_db()
|
||||||
|
db_module._conn = None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def client(fresh_db):
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||||
|
yield ac
|
||||||
|
|
||||||
|
|
||||||
|
async def _register_login(client, email="user@example.com", password="secret123"):
|
||||||
|
await client.post("/auth/register", json={"email": email, "password": password})
|
||||||
|
resp = await client.post("/auth/login", json={"email": email, "password": password})
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def _admin_token(client, email="admin@example.com", password="secret123"):
|
||||||
|
tokens = await _register_login(client, email, password)
|
||||||
|
me = await client.get("/users/me", headers={"Authorization": f"Bearer {tokens['access_token']}"})
|
||||||
|
db_module.get_conn().execute(
|
||||||
|
"UPDATE users SET role = 'admin' WHERE id = ?", [me.json()["id"]])
|
||||||
|
login = await client.post("/auth/login", json={"email": email, "password": password})
|
||||||
|
return login.json()["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /admin/stats
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_stats_as_admin(client):
|
||||||
|
await _register_login(client, "user1@example.com")
|
||||||
|
await _register_login(client, "user2@example.com")
|
||||||
|
token = await _admin_token(client)
|
||||||
|
|
||||||
|
resp = await client.get("/admin/stats", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["users"]["total"] == 3 # 2 users + 1 admin
|
||||||
|
assert "by_role" in data["users"]
|
||||||
|
assert "refresh_tokens" in data
|
||||||
|
|
||||||
|
|
||||||
|
async def test_stats_as_regular_user(client):
|
||||||
|
tokens = await _register_login(client)
|
||||||
|
resp = await client.get("/admin/stats", headers={"Authorization": f"Bearer {tokens['access_token']}"})
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
async def test_stats_unauthenticated(client):
|
||||||
|
resp = await client.get("/admin/stats")
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /admin/health/db
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_db_health_as_admin(client):
|
||||||
|
token = await _admin_token(client)
|
||||||
|
resp = await client.get("/admin/health/db", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["status"] == "ok"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_db_health_as_regular_user(client):
|
||||||
|
tokens = await _register_login(client)
|
||||||
|
resp = await client.get("/admin/health/db", headers={"Authorization": f"Bearer {tokens['access_token']}"})
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /admin/tokens/purge
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_purge_removes_revoked_tokens(client):
|
||||||
|
tokens = await _register_login(client, "user@example.com")
|
||||||
|
refresh_token = tokens["refresh_token"]
|
||||||
|
|
||||||
|
# Logout to revoke the token
|
||||||
|
await client.post("/auth/logout", json={"refresh_token": refresh_token})
|
||||||
|
|
||||||
|
token = await _admin_token(client)
|
||||||
|
resp = await client.post("/admin/tokens/purge", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["deleted"] >= 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_purge_nothing_to_remove(client):
|
||||||
|
token = await _admin_token(client)
|
||||||
|
resp = await client.post("/admin/tokens/purge", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
# Admin login issued one active token — nothing to purge
|
||||||
|
assert resp.json()["deleted"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_purge_as_regular_user(client):
|
||||||
|
tokens = await _register_login(client)
|
||||||
|
resp = await client.post("/admin/tokens/purge", headers={"Authorization": f"Bearer {tokens['access_token']}"})
|
||||||
|
assert resp.status_code == 403
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
"""Tests for AI endpoints — OpenRouter HTTP calls are fully mocked."""
|
||||||
|
import os
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
from httpx import AsyncClient, ASGITransport
|
||||||
|
|
||||||
|
from backend.app.main import app
|
||||||
|
from backend.app import db as db_module
|
||||||
|
|
||||||
|
os.environ.setdefault("JWT_SECRET", "test-secret-key-for-testing-only")
|
||||||
|
os.environ.setdefault("OPENROUTER_API_KEY", "test-key")
|
||||||
|
|
||||||
|
FAKE_MODELS = [
|
||||||
|
{"id": "openai/gpt-4o", "name": "GPT-4o", "context_length": 128000, "pricing": {"prompt": "0.000005"}},
|
||||||
|
{"id": "anthropic/claude-3-haiku", "name": "Claude 3 Haiku", "context_length": 200000, "pricing": {}},
|
||||||
|
]
|
||||||
|
|
||||||
|
FAKE_CHAT_RESPONSE = {
|
||||||
|
"id": "gen-abc123",
|
||||||
|
"model": "openai/gpt-4o",
|
||||||
|
"choices": [{"message": {"role": "assistant", "content": "Hello! How can I help?"}}],
|
||||||
|
"usage": {"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fresh_db():
|
||||||
|
db_module._conn = None
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
yield
|
||||||
|
db_module.close_db()
|
||||||
|
db_module._conn = None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def client(fresh_db):
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||||
|
yield ac
|
||||||
|
|
||||||
|
|
||||||
|
async def _user_token(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
resp = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
return resp.json()["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /ai/models
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_list_models(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch(
|
||||||
|
"backend.app.routers.ai.openrouter.list_models",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=FAKE_MODELS,
|
||||||
|
):
|
||||||
|
resp = await client.get("/ai/models", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert len(data) == 2
|
||||||
|
assert data[0]["id"] == "openai/gpt-4o"
|
||||||
|
assert data[1]["name"] == "Claude 3 Haiku"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_models_unauthenticated(client):
|
||||||
|
resp = await client.get("/ai/models")
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_models_upstream_error(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch(
|
||||||
|
"backend.app.routers.ai.openrouter.list_models",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
side_effect=Exception("Connection refused"),
|
||||||
|
):
|
||||||
|
resp = await client.get("/ai/models", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
|
||||||
|
assert resp.status_code == 502
|
||||||
|
assert "OpenRouter error" in resp.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /ai/chat
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_chat_success(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch(
|
||||||
|
"backend.app.routers.ai.openrouter.chat_completion",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=FAKE_CHAT_RESPONSE,
|
||||||
|
):
|
||||||
|
resp = await client.post(
|
||||||
|
"/ai/chat",
|
||||||
|
json={
|
||||||
|
"model": "openai/gpt-4o",
|
||||||
|
"messages": [{"role": "user", "content": "Hello"}],
|
||||||
|
},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["id"] == "gen-abc123"
|
||||||
|
assert data["model"] == "openai/gpt-4o"
|
||||||
|
assert data["content"] == "Hello! How can I help?"
|
||||||
|
assert data["usage"]["total_tokens"] == 18
|
||||||
|
|
||||||
|
|
||||||
|
async def test_chat_passes_parameters(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
mock = AsyncMock(return_value=FAKE_CHAT_RESPONSE)
|
||||||
|
with patch("backend.app.routers.ai.openrouter.chat_completion", new_callable=AsyncMock, return_value=FAKE_CHAT_RESPONSE) as mock:
|
||||||
|
await client.post(
|
||||||
|
"/ai/chat",
|
||||||
|
json={
|
||||||
|
"model": "anthropic/claude-3-haiku",
|
||||||
|
"messages": [{"role": "user", "content": "Hi"}],
|
||||||
|
"temperature": 0.3,
|
||||||
|
"max_tokens": 512,
|
||||||
|
},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
mock.assert_called_once_with(
|
||||||
|
model="anthropic/claude-3-haiku",
|
||||||
|
messages=[{"role": "user", "content": "Hi"}],
|
||||||
|
temperature=0.3,
|
||||||
|
max_tokens=512,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_chat_unauthenticated(client):
|
||||||
|
resp = await client.post(
|
||||||
|
"/ai/chat",
|
||||||
|
json={"model": "openai/gpt-4o", "messages": [{"role": "user", "content": "Hi"}]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_chat_upstream_error(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch(
|
||||||
|
"backend.app.routers.ai.openrouter.chat_completion",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
side_effect=Exception("timeout"),
|
||||||
|
):
|
||||||
|
resp = await client.post(
|
||||||
|
"/ai/chat",
|
||||||
|
json={"model": "openai/gpt-4o", "messages": [{"role": "user", "content": "Hi"}]},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
async def test_chat_malformed_upstream_response(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch(
|
||||||
|
"backend.app.routers.ai.openrouter.chat_completion",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value={"id": "x", "choices": []}, # empty choices
|
||||||
|
):
|
||||||
|
resp = await client.post(
|
||||||
|
"/ai/chat",
|
||||||
|
json={"model": "openai/gpt-4o", "messages": [{"role": "user", "content": "Hi"}]},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""Integration tests for auth endpoints using in-memory DuckDB."""
|
||||||
|
from backend.app.main import app
|
||||||
|
from backend.app import db as db_module
|
||||||
|
from httpx import AsyncClient, ASGITransport
|
||||||
|
import os
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
|
||||||
|
os.environ.setdefault("JWT_SECRET", "test-secret-key-for-testing-only")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fresh_db():
|
||||||
|
"""Reset the DB singleton to a fresh in-memory DB for each test."""
|
||||||
|
db_module._conn = None
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
yield
|
||||||
|
db_module.close_db()
|
||||||
|
db_module._conn = None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def client(fresh_db):
|
||||||
|
"""HTTP client wired to the app; explicitly depends on fresh_db to guarantee ordering."""
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||||
|
yield ac
|
||||||
|
|
||||||
|
|
||||||
|
async def test_register_success(client):
|
||||||
|
resp = await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
assert resp.status_code == 201
|
||||||
|
data = resp.json()
|
||||||
|
assert data["email"] == "user@example.com"
|
||||||
|
assert data["role"] == "user"
|
||||||
|
assert "id" in data
|
||||||
|
|
||||||
|
|
||||||
|
async def test_register_duplicate_email(client):
|
||||||
|
payload = {"email": "dup@example.com", "password": "secret123"}
|
||||||
|
await client.post("/auth/register", json=payload)
|
||||||
|
resp = await client.post("/auth/register", json=payload)
|
||||||
|
assert resp.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_success(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
resp = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert "access_token" in data
|
||||||
|
assert "refresh_token" in data
|
||||||
|
assert data["token_type"] == "bearer"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_wrong_password(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
resp = await client.post("/auth/login", json={"email": "user@example.com", "password": "wrong"})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_unknown_user(client):
|
||||||
|
resp = await client.post("/auth/login", json={"email": "nobody@example.com", "password": "x"})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_refresh_success(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
refresh_token = login.json()["refresh_token"]
|
||||||
|
|
||||||
|
resp = await client.post("/auth/refresh", json={"refresh_token": refresh_token})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert "access_token" in data
|
||||||
|
assert "refresh_token" in data
|
||||||
|
# New refresh token must differ (rotation)
|
||||||
|
assert data["refresh_token"] != refresh_token
|
||||||
|
|
||||||
|
|
||||||
|
async def test_refresh_revoked_token(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
refresh_token = login.json()["refresh_token"]
|
||||||
|
|
||||||
|
# Use once (rotates)
|
||||||
|
await client.post("/auth/refresh", json={"refresh_token": refresh_token})
|
||||||
|
# Try to reuse old token — must fail
|
||||||
|
resp = await client.post("/auth/refresh", json={"refresh_token": refresh_token})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_logout_success(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
refresh_token = login.json()["refresh_token"]
|
||||||
|
|
||||||
|
resp = await client.post("/auth/logout", json={"refresh_token": refresh_token})
|
||||||
|
assert resp.status_code == 204
|
||||||
|
|
||||||
|
# Refresh after logout must fail
|
||||||
|
resp2 = await client.post("/auth/refresh", json={"refresh_token": refresh_token})
|
||||||
|
assert resp2.status_code == 401
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Tests for DuckDB initialization and schema."""
|
||||||
|
import pytest
|
||||||
|
import duckdb
|
||||||
|
|
||||||
|
from backend.app import db as db_module
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fresh_db():
|
||||||
|
"""Use an in-memory DB for each test and reset global state."""
|
||||||
|
db_module._conn = None
|
||||||
|
yield
|
||||||
|
db_module.close_db()
|
||||||
|
db_module._conn = None
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_creates_users_table():
|
||||||
|
conn = db_module.init_db(":memory:")
|
||||||
|
result = conn.execute(
|
||||||
|
"SELECT table_name FROM information_schema.tables WHERE table_name = 'users'"
|
||||||
|
).fetchone()
|
||||||
|
assert result is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_creates_refresh_tokens_table():
|
||||||
|
conn = db_module.init_db(":memory:")
|
||||||
|
result = conn.execute(
|
||||||
|
"SELECT table_name FROM information_schema.tables WHERE table_name = 'refresh_tokens'"
|
||||||
|
).fetchone()
|
||||||
|
assert result is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_is_idempotent():
|
||||||
|
conn1 = db_module.init_db(":memory:")
|
||||||
|
conn2 = db_module.init_db(":memory:")
|
||||||
|
assert conn1 is conn2
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_conn_raises_before_init():
|
||||||
|
with pytest.raises(RuntimeError, match="not initialised"):
|
||||||
|
db_module.get_conn()
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_conn_returns_connection_after_init():
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
conn = db_module.get_conn()
|
||||||
|
assert conn is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_close_db_resets_connection():
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
db_module.close_db()
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
db_module.get_conn()
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
"""Tests for generate endpoints — all OpenRouter calls mocked."""
|
||||||
|
import os
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
from httpx import AsyncClient, ASGITransport
|
||||||
|
|
||||||
|
from backend.app.main import app
|
||||||
|
from backend.app import db as db_module
|
||||||
|
|
||||||
|
os.environ.setdefault("JWT_SECRET", "test-secret-key-for-testing-only")
|
||||||
|
os.environ.setdefault("OPENROUTER_API_KEY", "test-key")
|
||||||
|
|
||||||
|
FAKE_CHAT = {
|
||||||
|
"id": "gen-text-1",
|
||||||
|
"model": "openai/gpt-4o",
|
||||||
|
"choices": [{"message": {"role": "assistant", "content": "Once upon a time..."}}],
|
||||||
|
"usage": {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15},
|
||||||
|
}
|
||||||
|
|
||||||
|
FAKE_IMAGE = {
|
||||||
|
"id": "gen-img-1",
|
||||||
|
"model": "openai/dall-e-3",
|
||||||
|
"data": [
|
||||||
|
{"url": "https://example.com/image.png",
|
||||||
|
"revised_prompt": "A cat on the moon"},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
FAKE_VIDEO = {
|
||||||
|
"id": "gen-vid-1",
|
||||||
|
"model": "stability/stable-video",
|
||||||
|
"status": "queued",
|
||||||
|
"video_url": None,
|
||||||
|
"metadata": {"estimated_seconds": 30},
|
||||||
|
}
|
||||||
|
|
||||||
|
FAKE_VIDEO_DONE = {
|
||||||
|
"id": "gen-vid-2",
|
||||||
|
"model": "runway/gen-3",
|
||||||
|
"status": "completed",
|
||||||
|
"video_url": "https://example.com/video.mp4",
|
||||||
|
"metadata": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fresh_db():
|
||||||
|
db_module._conn = None
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
yield
|
||||||
|
db_module.close_db()
|
||||||
|
db_module._conn = None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def client(fresh_db):
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||||
|
yield ac
|
||||||
|
|
||||||
|
|
||||||
|
async def _user_token(client):
|
||||||
|
await client.post("/auth/register", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
resp = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
return resp.json()["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /generate/text
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_generate_text(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.chat_completion", new_callable=AsyncMock, return_value=FAKE_CHAT):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/text",
|
||||||
|
json={"model": "openai/gpt-4o", "prompt": "Tell me a story"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["content"] == "Once upon a time..."
|
||||||
|
assert data["id"] == "gen-text-1"
|
||||||
|
assert data["usage"]["total_tokens"] == 15
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_text_with_system_prompt(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
mock = AsyncMock(return_value=FAKE_CHAT)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.chat_completion", mock):
|
||||||
|
await client.post(
|
||||||
|
"/generate/text",
|
||||||
|
json={"model": "openai/gpt-4o", "prompt": "Hello",
|
||||||
|
"system_prompt": "Be concise."},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
call_messages = mock.call_args.kwargs["messages"]
|
||||||
|
assert call_messages[0] == {"role": "system", "content": "Be concise."}
|
||||||
|
assert call_messages[1] == {"role": "user", "content": "Hello"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_text_unauthenticated(client):
|
||||||
|
resp = await client.post("/generate/text", json={"model": "openai/gpt-4o", "prompt": "Hi"})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_text_upstream_error(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.chat_completion", new_callable=AsyncMock, side_effect=Exception("timeout")):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/text",
|
||||||
|
json={"model": "openai/gpt-4o", "prompt": "Hi"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /generate/image
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_generate_image(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.generate_image", new_callable=AsyncMock, return_value=FAKE_IMAGE):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/image",
|
||||||
|
json={"model": "openai/dall-e-3", "prompt": "A cat on the moon"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["id"] == "gen-img-1"
|
||||||
|
assert len(data["images"]) == 1
|
||||||
|
assert data["images"][0]["url"] == "https://example.com/image.png"
|
||||||
|
assert data["images"][0]["revised_prompt"] == "A cat on the moon"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_image_unauthenticated(client):
|
||||||
|
resp = await client.post("/generate/image", json={"model": "openai/dall-e-3", "prompt": "Hi"})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_image_upstream_error(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.generate_image", new_callable=AsyncMock, side_effect=Exception("rate limit")):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/image",
|
||||||
|
json={"model": "openai/dall-e-3", "prompt": "Hi"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /generate/video
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_generate_video(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.generate_video", new_callable=AsyncMock, return_value=FAKE_VIDEO):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/video",
|
||||||
|
json={"model": "stability/stable-video",
|
||||||
|
"prompt": "Ocean waves at sunset"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["id"] == "gen-vid-1"
|
||||||
|
assert data["status"] == "queued"
|
||||||
|
assert data["video_url"] is None
|
||||||
|
assert data["metadata"]["estimated_seconds"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_video_unauthenticated(client):
|
||||||
|
resp = await client.post("/generate/video", json={"model": "m", "prompt": "p"})
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_video_upstream_error(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.generate_video", new_callable=AsyncMock, side_effect=Exception("503")):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/video",
|
||||||
|
json={"model": "stability/stable-video", "prompt": "Hi"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# POST /generate/video/from-image
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_generate_video_from_image(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.generate_video_from_image", new_callable=AsyncMock, return_value=FAKE_VIDEO_DONE):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/video/from-image",
|
||||||
|
json={
|
||||||
|
"model": "runway/gen-3",
|
||||||
|
"image_url": "https://example.com/cat.jpg",
|
||||||
|
"prompt": "Cat runs across the room",
|
||||||
|
},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["status"] == "completed"
|
||||||
|
assert data["video_url"] == "https://example.com/video.mp4"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_video_from_image_unauthenticated(client):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/video/from-image",
|
||||||
|
json={"model": "m", "image_url": "https://example.com/img.jpg", "prompt": "p"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_video_from_image_upstream_error(client):
|
||||||
|
token = await _user_token(client)
|
||||||
|
with patch("backend.app.routers.generate.openrouter.generate_video_from_image", new_callable=AsyncMock, side_effect=Exception("error")):
|
||||||
|
resp = await client.post(
|
||||||
|
"/generate/video/from-image",
|
||||||
|
json={"model": "runway/gen-3",
|
||||||
|
"image_url": "https://example.com/img.jpg", "prompt": "p"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
"""Integration tests for user management endpoints."""
|
||||||
|
import os
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from httpx import AsyncClient, ASGITransport
|
||||||
|
|
||||||
|
from backend.app.main import app
|
||||||
|
from backend.app import db as db_module
|
||||||
|
|
||||||
|
os.environ.setdefault("JWT_SECRET", "test-secret-key-for-testing-only")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fresh_db():
|
||||||
|
db_module._conn = None
|
||||||
|
db_module.init_db(":memory:")
|
||||||
|
yield
|
||||||
|
db_module.close_db()
|
||||||
|
db_module._conn = None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def client(fresh_db):
|
||||||
|
transport = ASGITransport(app=app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||||
|
yield ac
|
||||||
|
|
||||||
|
|
||||||
|
async def _register_and_login(client, email="user@example.com", password="secret123"):
|
||||||
|
await client.post("/auth/register", json={"email": email, "password": password})
|
||||||
|
resp = await client.post("/auth/login", json={"email": email, "password": password})
|
||||||
|
return resp.json()["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
async def _make_admin(user_id: str):
|
||||||
|
"""Directly set a user's role to admin in the DB."""
|
||||||
|
conn = db_module.get_conn()
|
||||||
|
conn.execute("UPDATE users SET role = 'admin' WHERE id = ?", [user_id])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /users/me
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_get_me(client):
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
resp = await client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["email"] == "user@example.com"
|
||||||
|
assert data["role"] == "user"
|
||||||
|
assert "id" in data
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_me_unauthenticated(client):
|
||||||
|
resp = await client.get("/users/me")
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# PUT /users/me
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_update_me_email(client):
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
resp = await client.put(
|
||||||
|
"/users/me",
|
||||||
|
json={"email": "new@example.com"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["email"] == "new@example.com"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_update_me_password(client):
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
resp = await client.put(
|
||||||
|
"/users/me",
|
||||||
|
json={"password": "newpassword123"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
# Verify new password works for login
|
||||||
|
login = await client.post(
|
||||||
|
"/auth/login", json={"email": "user@example.com", "password": "newpassword123"}
|
||||||
|
)
|
||||||
|
assert login.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
async def test_update_me_duplicate_email(client):
|
||||||
|
await _register_and_login(client, "other@example.com")
|
||||||
|
token = await _register_and_login(client, "user@example.com")
|
||||||
|
resp = await client.put(
|
||||||
|
"/users/me",
|
||||||
|
json={"email": "other@example.com"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# GET /users (admin only)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_list_users_as_admin(client):
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
me = await client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
await _make_admin(me.json()["id"])
|
||||||
|
|
||||||
|
# Re-login to get a token with admin role
|
||||||
|
login = await client.post(
|
||||||
|
"/auth/login", json={"email": "user@example.com", "password": "secret123"}
|
||||||
|
)
|
||||||
|
admin_token = login.json()["access_token"]
|
||||||
|
resp = await client.get("/users", headers={"Authorization": f"Bearer {admin_token}"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert isinstance(resp.json(), list)
|
||||||
|
assert len(resp.json()) == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_list_users_as_regular_user(client):
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
resp = await client.get("/users", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# DELETE /users/{id} (admin only)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_delete_user_as_admin(client):
|
||||||
|
# Register target user
|
||||||
|
await client.post("/auth/register", json={"email": "target@example.com", "password": "secret123"})
|
||||||
|
target_resp = await client.post("/auth/login", json={"email": "target@example.com", "password": "secret123"})
|
||||||
|
target_token = target_resp.json()["access_token"]
|
||||||
|
target_me = await client.get("/users/me", headers={"Authorization": f"Bearer {target_token}"})
|
||||||
|
target_id = target_me.json()["id"]
|
||||||
|
|
||||||
|
# Register admin
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
me = await client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
await _make_admin(me.json()["id"])
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
admin_token = login.json()["access_token"]
|
||||||
|
|
||||||
|
resp = await client.delete(f"/users/{target_id}", headers={"Authorization": f"Bearer {admin_token}"})
|
||||||
|
assert resp.status_code == 204
|
||||||
|
|
||||||
|
|
||||||
|
async def test_delete_own_account_forbidden(client):
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
me = await client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
user_id = me.json()["id"]
|
||||||
|
await _make_admin(user_id)
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
admin_token = login.json()["access_token"]
|
||||||
|
|
||||||
|
resp = await client.delete(f"/users/{user_id}", headers={"Authorization": f"Bearer {admin_token}"})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# PUT /users/{id}/role (admin only)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def test_set_role_as_admin(client):
|
||||||
|
# Register target
|
||||||
|
await client.post("/auth/register", json={"email": "target@example.com", "password": "secret123"})
|
||||||
|
target_resp = await client.post("/auth/login", json={"email": "target@example.com", "password": "secret123"})
|
||||||
|
target_me = await client.get("/users/me", headers={"Authorization": f"Bearer {target_resp.json()['access_token']}"})
|
||||||
|
target_id = target_me.json()["id"]
|
||||||
|
|
||||||
|
# Register admin
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
me = await client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
await _make_admin(me.json()["id"])
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
admin_token = login.json()["access_token"]
|
||||||
|
|
||||||
|
resp = await client.put(
|
||||||
|
f"/users/{target_id}/role",
|
||||||
|
json={"role": "admin"},
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["role"] == "admin"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_set_invalid_role(client):
|
||||||
|
await client.post("/auth/register", json={"email": "target@example.com", "password": "secret123"})
|
||||||
|
target_resp = await client.post("/auth/login", json={"email": "target@example.com", "password": "secret123"})
|
||||||
|
target_me = await client.get("/users/me", headers={"Authorization": f"Bearer {target_resp.json()['access_token']}"})
|
||||||
|
target_id = target_me.json()["id"]
|
||||||
|
|
||||||
|
token = await _register_and_login(client)
|
||||||
|
me = await client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
|
await _make_admin(me.json()["id"])
|
||||||
|
login = await client.post("/auth/login", json={"email": "user@example.com", "password": "secret123"})
|
||||||
|
admin_token = login.json()["access_token"]
|
||||||
|
|
||||||
|
resp = await client.put(
|
||||||
|
f"/users/{target_id}/role",
|
||||||
|
json={"role": "superuser"},
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 422
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[tool.pytest.ini_options]
|
||||||
|
asyncio_mode = "auto"
|
||||||
|
testpaths = ["backend/tests", "frontend/tests"]
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
annotated-doc==0.0.4
|
||||||
|
annotated-types==0.7.0
|
||||||
|
anyio==4.13.0
|
||||||
|
backports.asyncio.runner==1.2.0
|
||||||
|
bcrypt==3.2.2
|
||||||
|
blinker==1.9.0
|
||||||
|
certifi==2026.4.22
|
||||||
|
cffi==2.0.0
|
||||||
|
click==8.3.3
|
||||||
|
colorama==0.4.6
|
||||||
|
cryptography==47.0.0
|
||||||
|
dnspython==2.8.0
|
||||||
|
duckdb==1.5.2
|
||||||
|
ecdsa==0.19.2
|
||||||
|
email-validator==2.3.0
|
||||||
|
exceptiongroup==1.3.1
|
||||||
|
fastapi==0.136.1
|
||||||
|
Flask==3.1.3
|
||||||
|
h11==0.16.0
|
||||||
|
httpcore==1.0.9
|
||||||
|
httpx==0.28.1
|
||||||
|
idna==3.13
|
||||||
|
iniconfig==2.3.0
|
||||||
|
itsdangerous==2.2.0
|
||||||
|
Jinja2==3.1.6
|
||||||
|
MarkupSafe==3.0.3
|
||||||
|
packaging==26.2
|
||||||
|
passlib==1.7.4
|
||||||
|
pluggy==1.6.0
|
||||||
|
pyasn1==0.6.3
|
||||||
|
pycparser==3.0
|
||||||
|
pydantic==2.13.3
|
||||||
|
pydantic_core==2.46.3
|
||||||
|
Pygments==2.20.0
|
||||||
|
pytest==9.0.3
|
||||||
|
pytest-asyncio==1.3.0
|
||||||
|
python-dotenv==1.2.2
|
||||||
|
python-jose==3.5.0
|
||||||
|
rsa==4.9.1
|
||||||
|
six==1.17.0
|
||||||
|
starlette==1.0.0
|
||||||
|
tomli==2.4.1
|
||||||
|
typing-inspection==0.4.2
|
||||||
|
typing_extensions==4.15.0
|
||||||
|
uvicorn==0.46.0
|
||||||
|
Werkzeug==3.1.8
|
||||||
Reference in New Issue
Block a user