From 72b988b79b76caa86f8732837a9df029f4726dd8 Mon Sep 17 00:00:00 2001 From: mohamad Date: Wed, 14 May 2025 00:24:51 +0200 Subject: [PATCH] Refactor authentication and database session handling; update user schemas for enhanced functionality and compatibility with FastAPI-Users. --- be/app/api/v1/endpoints/health.py | 4 ++-- be/app/auth.py | 2 +- be/app/config.py | 4 ++-- be/app/database.py | 7 +++++-- be/app/main.py | 7 ++++--- be/app/schemas/user.py | 9 ++++++--- 6 files changed, 20 insertions(+), 13 deletions(-) diff --git a/be/app/api/v1/endpoints/health.py b/be/app/api/v1/endpoints/health.py index 6cf872e..1d18f3c 100644 --- a/be/app/api/v1/endpoints/health.py +++ b/be/app/api/v1/endpoints/health.py @@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql import text -from app.database import get_db +from app.database import get_async_session from app.schemas.health import HealthStatus from app.core.exceptions import DatabaseConnectionError @@ -18,7 +18,7 @@ router = APIRouter() description="Checks the operational status of the API and its connection to the database.", tags=["Health"] ) -async def check_health(db: AsyncSession = Depends(get_db)): +async def check_health(db: AsyncSession = Depends(get_async_session)): """ Health check endpoint. Verifies API reachability and database connection. """ diff --git a/be/app/auth.py b/be/app/auth.py index 6df0042..6569762 100644 --- a/be/app/auth.py +++ b/be/app/auth.py @@ -1,12 +1,12 @@ from typing import Optional from fastapi import Depends, Request +from fastapi.security import OAuth2PasswordRequestForm from fastapi_users import BaseUserManager, FastAPIUsers, IntegerIDMixin from fastapi_users.authentication import ( AuthenticationBackend, BearerTransport, JWTStrategy, - OAuth2PasswordRequestForm, ) from fastapi_users.db import SQLAlchemyUserDatabase from sqlalchemy.ext.asyncio import AsyncSession diff --git a/be/app/config.py b/be/app/config.py index 554e576..162f4aa 100644 --- a/be/app/config.py +++ b/be/app/config.py @@ -82,8 +82,8 @@ Organic Bananas HEALTH_STATUS_ERROR: str = "error" # --- Auth Settings --- (These are largely handled by FastAPI-Users now) - # OAUTH2_TOKEN_URL: str = "/api/v1/auth/login" # FastAPI-Users has its own token URL - # TOKEN_TYPE: str = "bearer" + OAUTH2_TOKEN_URL: str = "/api/v1/auth/login" # FastAPI-Users has its own token URL + TOKEN_TYPE: str = "bearer" # AUTH_HEADER_PREFIX: str = "Bearer" # AUTH_HEADER_NAME: str = "WWW-Authenticate" # AUTH_CREDENTIALS_ERROR: str = "Could not validate credentials" diff --git a/be/app/database.py b/be/app/database.py index d1bda5a..f14bb93 100644 --- a/be/app/database.py +++ b/be/app/database.py @@ -30,7 +30,7 @@ AsyncSessionLocal = sessionmaker( Base = declarative_base() # Dependency to get DB session in path operations -async def get_db() -> AsyncSession: # type: ignore +async def get_async_session() -> AsyncSession: # type: ignore """ Dependency function that yields an AsyncSession. Ensures the session is closed after the request. @@ -44,4 +44,7 @@ async def get_db() -> AsyncSession: # type: ignore await session.rollback() raise finally: - await session.close() # Not strictly necessary with async context manager, but explicit \ No newline at end of file + await session.close() # Not strictly necessary with async context manager, but explicit + +# Alias for backward compatibility +get_db = get_async_session \ No newline at end of file diff --git a/be/app/main.py b/be/app/main.py index 248abb6..f902b89 100644 --- a/be/app/main.py +++ b/be/app/main.py @@ -13,6 +13,7 @@ from app.core.api_config import API_METADATA, API_TAGS from app.auth import fastapi_users, auth_backend from app.models import User from app.api.auth.oauth import router as oauth_router +from app.schemas.user import UserPublic, UserCreate, UserUpdate # Initialize Sentry sentry_sdk.init( @@ -77,7 +78,7 @@ app.include_router( tags=["auth"], ) app.include_router( - fastapi_users.get_register_router(), + fastapi_users.get_register_router(UserPublic, UserCreate), prefix="/auth", tags=["auth"], ) @@ -87,12 +88,12 @@ app.include_router( tags=["auth"], ) app.include_router( - fastapi_users.get_verify_router(), + fastapi_users.get_verify_router(UserPublic), prefix="/auth", tags=["auth"], ) app.include_router( - fastapi_users.get_users_router(), + fastapi_users.get_users_router(UserPublic, UserUpdate), prefix="/users", tags=["users"], ) diff --git a/be/app/schemas/user.py b/be/app/schemas/user.py index be22574..b26b727 100644 --- a/be/app/schemas/user.py +++ b/be/app/schemas/user.py @@ -12,9 +12,12 @@ class UserBase(BaseModel): class UserCreate(UserBase): password: str -# Properties to receive via API on update (optional, add later if needed) -# class UserUpdate(UserBase): -# password: Optional[str] = None +# Properties to receive via API on update +class UserUpdate(UserBase): + password: Optional[str] = None + is_active: Optional[bool] = None + is_superuser: Optional[bool] = None + is_verified: Optional[bool] = None # Properties stored in DB class UserInDBBase(UserBase):