fastapi-debug-toolbar icon indicating copy to clipboard operation
fastapi-debug-toolbar copied to clipboard

Issue with fastapi_users current active user dependency

Open BhuwanPandey opened this issue 2 years ago • 3 comments

BhuwanPandey avatar May 15 '23 14:05 BhuwanPandey

Please describe the issue in detail.

mongkok avatar Jun 27 '23 11:06 mongkok

I have used fastapi-users for handling authentication mechanism as well as used async postgres connection in my project.

** file structure look like

db.py

engine = create_async_engine(settings.DATABASE_URL)
async_session_maker = async_sessionmaker(
    engine, class_=AsyncSession, expire_on_commit=False
)

async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_maker() as session:
        yield session

async def get_user_db(session: AsyncSession = Depends(get_async_session)):
    yield SQLAlchemyUserDatabase(session, User)


async def get_db(session: AsyncSession = Depends(get_async_session)):
    try:
        yield session
    finally:
        await session.close()


class SQLAlchemyPanel(BasePanel):
    async def add_engines(self, request: Request):
        self.engines.add(engine)

main.py


from .routers import user_routers
from fastapi import FastAPI, Request, status

app = FastAPI(debug=True)
app.add_middleware(
    DebugToolbarMiddleware,
    panels=["debug_toolbar.panels.sqlalchemy.SQLAlchemyPanel"],
)
app.include_router(user_routers)

router.py


from .db  import get_async_session
from fastapi import APIRouter
from src.users.managers import (
    auth_backend,
    cookie_backend,
    current_active_user,
    current_active_user_optional,
    fastapi_users)


user_routers = APIRouter()
user_routers.include_router(
    fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)

@user_routers.get("/users/me", response_model=UserMeInfo, tags=["users"])
async def get_my_info(
    user=Depends(current_active_user),
    async_session: AsyncSession = Depends(get_async_session),
):
    my_details = await UserService.get_me(user.id.hex, async_session)
    return my_details
----------------       Problem -----------------------------------
  1. On visting users/me endpoint, when user is not authenticated, it raises

File "/usr/local/lib/python3.10/site-packages/fastapi_users/authentication/authenticator.py", line 187, in _authenticate raise HTTPException(status_code=status_code) fastapi.exceptions.HTTPException

  1. Sql queries doesnot show on sqlalchemy field of debugtool bar

BhuwanPandey avatar Jul 28 '23 12:07 BhuwanPandey

Oh I'm having the same issue with tortoise ORM. Any luck on your side ?

Anihouvi avatar Oct 28 '23 19:10 Anihouvi