Backend API: auth, projects/images/annotations, R2 presign, tracing, thumbnails, pagination, tests, docs

This commit is contained in:
hailt 2026-11-12 15:12:26 +07:00
parent 5c5deed2f5
commit f8ed08b854
49 changed files with 2626 additions and 0 deletions

76
tests/test_auth.py Normal file
View file

@ -0,0 +1,76 @@
"""Auth: hashing, tokens, and route protection (no dev-DB writes)."""
import pytest
import pytest_asyncio
from fastapi.security import HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from models import User
from src.core.db import Base
from src.core.security import (
create_token,
decode_token,
get_current_user,
hash_password,
verify_password,
)
from src.main import app
from fastapi.testclient import TestClient
@pytest_asyncio.fixture
async def db():
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield async_sessionmaker(engine, expire_on_commit=False)
await engine.dispose()
def test_password_roundtrip():
h = hash_password("Admin123!")
assert verify_password("Admin123!", h)
assert not verify_password("wrong", h)
assert not verify_password("x", "")
def test_token_roundtrip():
tok = create_token("u1", "admin")
payload = decode_token(tok)
assert payload and payload["sub"] == "u1" and payload["role"] == "admin"
assert decode_token("garbage") is None
@pytest.mark.asyncio
async def test_current_user_rejects_anonymous(db):
from fastapi import HTTPException
async with db() as s:
with pytest.raises(HTTPException) as e:
await get_current_user(None, s)
assert e.value.status_code == 401
@pytest.mark.asyncio
async def test_current_user_accepts_seeded(db):
async with db() as s:
s.add(User(id="u1", email="a@x.io", name="A", role="admin",
status="active", password_hash=hash_password("pw"),
assigned_project_ids=[]))
await s.commit()
tok = create_token("u1", "admin")
creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=tok)
user = await get_current_user(creds, s)
assert user.email == "a@x.io"
def test_protected_routes_reject_missing_token():
with TestClient(app) as c:
assert c.get("/api/v1/projects").status_code == 401
assert c.get("/api/v1/activities").status_code == 401
assert c.get("/api/v1/projects/x/images").status_code == 401
def test_login_rejects_unknown_user():
with TestClient(app) as c:
r = c.post("/api/v1/auth/login",
json={"email": "no-such-user@example.com", "password": "x"})
assert r.status_code == 401