Skip to content

Refactor auth service to use FastAPI dependency injection chain #529

@lbedner

Description

@lbedner

Problem

Auth routes manually instantiate UserService(db) in every endpoint handler:

# app/components/backend/api/auth/router.py — repeated in every route
async def register(user_data: UserCreate, db: AsyncSession = Depends(get_async_db)):
    user_service = UserService(db)
    ...

This creates boilerplate and bypasses FastAPI's dependency injection system. The service is stateful (holds a db session) but isn't wired as a proper dependency.

Proposed Change

Add a get_user_service dependency that composes get_async_db, so routes receive the service directly:

# app/components/backend/api/deps.py (or auth-specific deps)
async def get_user_service(
    db: AsyncSession = Depends(get_async_db),
) -> UserService:
    return UserService(db)

Then routes simplify to:

@router.post("/register", response_model=UserResponse)
async def register(
    user_data: UserCreate,
    user_service: UserService = Depends(get_user_service),
):
    existing_user = await user_service.get_user_by_email(user_data.email)
    ...

Similarly, get_current_user_from_token in auth_service.py manually creates a UserService(db) — this should also use the injected service.

Files to Modify

  • app/components/backend/api/deps.py — add get_user_service dependency
  • app/components/backend/api/auth/router.py — replace manual UserService(db) with Depends(get_user_service) in all 8 route handlers
  • app/services/auth/auth_service.py — update get_current_user_from_token to accept UserService instead of raw db

Benefits

  • Eliminates repeated UserService(db) boilerplate across 8 endpoints
  • Proper FastAPI DI — services are composable and testable via app.dependency_overrides
  • Easier to mock in tests (override one dependency vs patching constructors)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions