FastAPI Integration: Dependencies

AuthTuna provides powerful FastAPI dependencies to handle authentication and authorization efficiently.

`get_current_user`

The standard authentication dependency. It retrieves the complete User object from the database or raises a 401 Unauthorized error.

from fastapi import Depends
from authtuna.integrations import get_current_user
from authtuna.core.database import User

@app.get("/profile")
async def get_my_profile(user: User = Depends(get_current_user)):
    return {"username": user.username, "roles": [r.name for r in user.roles]}

`get_current_user_optional`

Used for routes accessible to both authenticated and unauthenticated users. Returns User or None.

from typing import Optional
from authtuna.integrations import get_current_user_optional

@app.get("/")
async def homepage(user: Optional[User] = Depends(get_current_user_optional)):
    if user:
        return f"Hello, {user.username}"
    return "Hello, Guest"