diff --git a/api/src/api/main.py b/api/src/api/main.py index 31d1534..0330420 100644 --- a/api/src/api/main.py +++ b/api/src/api/main.py @@ -1,10 +1,8 @@ -from fastapi import FastAPI, HTTPException, status +from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from api.core.config import settings -from api.models.auth import DevTokenRequest, LoginResponse -from api.routers import sculptures -from api.services.auth.service import AuthService +from api.routers import auth, sculptures, users app = FastAPI( title=settings.PROJECT_NAME, @@ -22,10 +20,10 @@ app.add_middleware( ) # Register routers +app.include_router(auth.router) +app.include_router(users.router) app.include_router(sculptures.router) -auth_service = AuthService() - @app.get("/health", tags=["System"]) async def health_check() -> dict[str, str]: @@ -38,32 +36,3 @@ async def health_check() -> dict[str, str]: "version": settings.VERSION, "env": settings.ENV, } - - -@app.post( - "/auth/dev-token", - response_model=LoginResponse, - tags=["Authentication"], - summary="Development SSO Bypass Token Generation", -) -async def generate_dev_token(payload: DevTokenRequest) -> LoginResponse: - """ - Generate signed JWT for testing without contacting external OAuth providers. - Available only when ENV is not 'production'. - """ - if settings.ENV == "production": - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Development token generation disabled in production environment.", - ) - - # Use deterministic mock ID based on email - import hashlib - import uuid - - deterministic_uuid = uuid.UUID(hashlib.md5(payload.email.encode("utf-8")).hexdigest()) - - return auth_service.create_access_token( - user_id=str(deterministic_uuid), - email=payload.email, - ) diff --git a/api/src/api/routers/auth.py b/api/src/api/routers/auth.py new file mode 100644 index 0000000..593db93 --- /dev/null +++ b/api/src/api/routers/auth.py @@ -0,0 +1,95 @@ +import hashlib +import uuid +from typing import Annotated + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from api.core.config import settings +from api.database.session import get_db_session +from api.db_models.user import UserDB +from api.models.auth import DevTokenRequest, LoginRequest, LoginResponse +from api.routers.deps import auth_service + +router = APIRouter(prefix="/auth", tags=["Authentication"]) + + +@router.post( + "/login", + response_model=LoginResponse, + summary="Google SSO Authentication", + description="Exchange a Google OAuth ID token for a system-issued JWT access token.", +) +async def login_user( + payload: LoginRequest, + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> LoginResponse: + try: + identity = await auth_service.authenticate_sso(payload.id_token) + except ValueError as err: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=f"Invalid token provided: {err}", + ) from err + + # Provision or retrieve user + result = await db.execute(select(UserDB).where(UserDB.email == identity.email)) + user = result.scalars().first() + + if not user: + user_uuid = uuid.UUID(hashlib.md5(identity.email.encode("utf-8")).hexdigest()) + user = UserDB( + id=user_uuid, + name=identity.name, + email=identity.email, + trust_score=0.5, + ) + db.add(user) + await db.commit() + await db.refresh(user) + + return auth_service.create_access_token( + user_id=str(user.id), + email=user.email, + ) + + +@router.post( + "/dev-token", + response_model=LoginResponse, + summary="Development SSO Bypass Token Generation", + description="Generate signed JWT for testing without contacting external OAuth providers.", +) +async def generate_dev_token( + payload: DevTokenRequest, + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> LoginResponse: + if settings.ENV == "production": + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Development token generation disabled in production environment.", + ) + + # Deterministic UUID based on email + user_uuid = uuid.UUID(hashlib.md5(payload.email.encode("utf-8")).hexdigest()) + + # Ensure user exists in database + result = await db.execute(select(UserDB).where(UserDB.email == payload.email)) + user = result.scalars().first() + + if not user: + user = UserDB( + id=user_uuid, + name=payload.name, + email=payload.email, + trust_score=0.5, + ) + db.add(user) + await db.commit() + await db.refresh(user) + + return auth_service.create_access_token( + user_id=str(user.id), + email=user.email, + ) diff --git a/api/src/api/routers/deps.py b/api/src/api/routers/deps.py new file mode 100644 index 0000000..90bafd5 --- /dev/null +++ b/api/src/api/routers/deps.py @@ -0,0 +1,66 @@ +import uuid +from typing import Annotated + +import jwt +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from sqlalchemy.ext.asyncio import AsyncSession + +from api.database.session import get_db_session +from api.db_models.user import UserDB +from api.services.auth.service import AuthService + +security = HTTPBearer(auto_error=False) +auth_service = AuthService() + + +async def get_current_user( + credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)], + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> UserDB: + """ + FastAPI dependency validating Bearer JWT token and returning authenticated UserDB entity. + """ + if credentials is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Authentication token missing or expired.", + headers={"WWW-Authenticate": "Bearer"}, + ) + + token = credentials.credentials + try: + payload = auth_service.decode_access_token(token) + except jwt.PyJWTError as err: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Authentication token missing or expired.", + headers={"WWW-Authenticate": "Bearer"}, + ) from err + + user_id_str = payload.get("sub") + if not user_id_str: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid token payload: missing subject.", + headers={"WWW-Authenticate": "Bearer"}, + ) + + try: + user_uuid = uuid.UUID(user_id_str) + except ValueError as err: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid user ID format in token.", + headers={"WWW-Authenticate": "Bearer"}, + ) from err + + user = await db.get(UserDB, user_uuid) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="User associated with token not found.", + headers={"WWW-Authenticate": "Bearer"}, + ) + + return user diff --git a/api/src/api/routers/users.py b/api/src/api/routers/users.py new file mode 100644 index 0000000..c27b0cf --- /dev/null +++ b/api/src/api/routers/users.py @@ -0,0 +1,73 @@ +from typing import Annotated + +from fastapi import APIRouter, Depends +from pydantic import EmailStr, HttpUrl, TypeAdapter +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from api.database.session import get_db_session +from api.db_models.checkin import CheckInDB +from api.db_models.user import UserDB +from api.models.checkin import CheckInRecord +from api.models.user import User +from api.routers.deps import get_current_user + +router = APIRouter(prefix="/users", tags=["Users"]) + +email_adapter = TypeAdapter(EmailStr) +http_url_adapter = TypeAdapter(HttpUrl) + + +@router.get( + "/me", + response_model=User, + summary="Retrieve Current User Profile", + description="Get details about the authenticated user, including their community trust score.", +) +async def get_my_profile( + current_user: Annotated[UserDB, Depends(get_current_user)], + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> User: + # Calculate count of unique verified captures + count_stmt = select(func.count(CheckInDB.id)).where(CheckInDB.user_id == current_user.id) + result = await db.execute(count_stmt) + captured_count = result.scalar() or 0 + + return User( + id=current_user.id, + name=current_user.name, + email=email_adapter.validate_python(current_user.email), + trust_score=current_user.trust_score, + captured_count=captured_count, + ) + + +@router.get( + "/me/collection", + response_model=list[CheckInRecord], + summary="Get User's Unlocked Sculptures", + description="Returns the user's progress tracking which cat sculptures they have successfully captured.", +) +async def get_my_collection( + current_user: Annotated[UserDB, Depends(get_current_user)], + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> list[CheckInRecord]: + stmt = ( + select(CheckInDB) + .where(CheckInDB.user_id == current_user.id) + .order_by(CheckInDB.captured_at.desc()) + ) + result = await db.execute(stmt) + check_ins = result.scalars().all() + + return [ + CheckInRecord( + sculpture_id=item.sculpture_id, + unlocked_at=item.captured_at, + checkin_photo_url=( + http_url_adapter.validate_python(item.photo_url) if item.photo_url else None + ), + similarity_score=item.similarity_score, + ) + for item in check_ins + ] diff --git a/api/tests/integration/test_auth_and_users_router.py b/api/tests/integration/test_auth_and_users_router.py new file mode 100644 index 0000000..7f9ab39 --- /dev/null +++ b/api/tests/integration/test_auth_and_users_router.py @@ -0,0 +1,104 @@ +import uuid + +import pytest +from httpx import AsyncClient + +from api.core.config import settings +from api.database.seed import INITIAL_SCULPTURES +from api.db_models.checkin import CheckInDB +from tests.conftest import TestAsyncSessionLocal + + +@pytest.mark.asyncio +async def test_auth_login_success(async_client: AsyncClient): + payload = {"id_token": "valid-mock-token"} + response = await async_client.post("/auth/login", json=payload) + assert response.status_code == 200 + + data = response.json() + assert "access_token" in data + assert data["token_type"] == "Bearer" + assert data["expires_in"] > 0 + + +@pytest.mark.asyncio +async def test_auth_login_invalid_token(async_client: AsyncClient): + payload = {"id_token": "invalid-token"} + response = await async_client.post("/auth/login", json=payload) + assert response.status_code == 401 + assert "Invalid token provided" in response.json()["detail"] + + +@pytest.mark.asyncio +async def test_dev_token_production_disabled(async_client: AsyncClient): + original_env = settings.ENV + try: + settings.ENV = "production" + payload = {"email": "blocked@cali.gov.co", "name": "Blocked"} + response = await async_client.post("/auth/dev-token", json=payload) + assert response.status_code == 403 + assert "disabled in production" in response.json()["detail"] + finally: + settings.ENV = original_env + + +@pytest.mark.asyncio +async def test_users_me_unauthorized(async_client: AsyncClient): + # Missing header + res1 = await async_client.get("/users/me") + assert res1.status_code == 401 + + # Invalid token + res2 = await async_client.get("/users/me", headers={"Authorization": "Bearer bad.token.here"}) + assert res2.status_code == 401 + + +@pytest.mark.asyncio +async def test_users_me_and_collection_flow(async_client: AsyncClient): + test_email = f"explorer.{uuid.uuid4().hex[:8]}@example.com" + token_resp = await async_client.post( + "/auth/dev-token", json={"email": test_email, "name": "Collection Explorer"} + ) + assert token_resp.status_code == 200 + token = token_resp.json()["access_token"] + headers = {"Authorization": f"Bearer {token}"} + + # 1. Profile initially has 0 captures + profile_resp = await async_client.get("/users/me", headers=headers) + assert profile_resp.status_code == 200 + profile_data = profile_resp.json() + assert profile_data["email"] == test_email + assert profile_data["name"] == "Collection Explorer" + assert profile_data["captured_count"] == 0 + user_id = uuid.UUID(profile_data["id"]) + + # 2. Collection initially empty + col_resp = await async_client.get("/users/me/collection", headers=headers) + assert col_resp.status_code == 200 + assert col_resp.json() == [] + + # 3. Add a check-in record directly via DB session + sculpture_id = INITIAL_SCULPTURES[0]["id"] + async with TestAsyncSessionLocal() as session: + check_in = CheckInDB( + user_id=user_id, + sculpture_id=sculpture_id, + photo_url="https://cdn.gatos.cali.gov.co/uploads/test.jpg", + similarity_score=0.92, + ) + session.add(check_in) + await session.commit() + + # 4. Collection now has 1 capture + col_resp2 = await async_client.get("/users/me/collection", headers=headers) + assert col_resp2.status_code == 200 + items = col_resp2.json() + assert len(items) == 1 + assert items[0]["sculpture_id"] == str(sculpture_id) + assert items[0]["similarity_score"] == 0.92 + assert items[0]["checkin_photo_url"] == "https://cdn.gatos.cali.gov.co/uploads/test.jpg" + + # 5. Profile captured_count reflects the new capture + profile_resp2 = await async_client.get("/users/me", headers=headers) + assert profile_resp2.status_code == 200 + assert profile_resp2.json()["captured_count"] == 1 diff --git a/api/tests/integration/test_health_and_auth.py b/api/tests/integration/test_health_and_auth.py index 3da9b38..0de4133 100644 --- a/api/tests/integration/test_health_and_auth.py +++ b/api/tests/integration/test_health_and_auth.py @@ -1,7 +1,7 @@ import pytest from httpx import AsyncClient -from api.main import auth_service +from api.routers.deps import auth_service @pytest.mark.asyncio diff --git a/todo.txt b/todo.txt index b2fecc2..2c7b564 100644 --- a/todo.txt +++ b/todo.txt @@ -5,8 +5,8 @@ x 2026-10-13 (A) Initialize Alembic and create initial schema migration in api/a x 2026-10-13 (A) Create seed script and populate 3 historical cat sculptures in api/scripts/seed_sculptures.py +api @db x 2026-10-13 (A) Establish automated test suite with pytest-asyncio and SQLite/Postgres harness in api/tests/ +test @api x 2026-10-13 (A) Draft Architectural Decision Record for Jev Cascade Triage in docs/adr/001-jev-cascade-triage.md +docs @arch -(A) Implement Pydantic v2 domain schemas matching openapi_unified.yaml in api/schemas.py +api @backend -(A) Implement IdentityProvider protocol and mock local auth provider in api/auth.py +api @auth +x 2026-10-15 (A) Implement Pydantic v2 domain schemas matching openapi_unified.yaml in api/models/ +api @backend +x 2026-10-15 (A) Implement IdentityProvider protocol, auth router, and users profile router in api/routers/ +api @auth x 2026-10-13 (A) Implement Sculptures read router with spatial coordinate serialization in api/routers/sculptures.py +api @backend (B) Implement Check-In verification engine with spatial distance threshold and cosine similarity threshold in api/services/checkin.py +api @backend (B) Implement Check-In router with idempotency and streak tracking in api/routers/checkins.py +api @backend