forked from cardosofelipe/fast-next-template
Refactor backend to adopt async patterns across services, API routes, and CRUD operations
- Migrated database sessions and operations to `AsyncSession` for full async support. - Updated all service methods and dependencies (`get_db` to `get_async_db`) to support async logic. - Refactored admin, user, organization, session-related CRUD methods, and routes with await syntax. - Improved consistency and performance with async SQLAlchemy patterns. - Enhanced logging and error handling for async context.
This commit is contained in:
24
backend/app/api/dependencies/auth.py
Normal file → Executable file
24
backend/app/api/dependencies/auth.py
Normal file → Executable file
@@ -3,18 +3,19 @@ from typing import Optional
|
||||
from fastapi import Depends, HTTPException, status, Header
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from fastapi.security.utils import get_authorization_scheme_param
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.auth import get_token_data, TokenExpiredError, TokenInvalidError
|
||||
from app.core.database import get_db
|
||||
from app.core.database_async import get_async_db
|
||||
from app.models.user import User
|
||||
|
||||
# OAuth2 configuration
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
|
||||
def get_current_user(
|
||||
db: Session = Depends(get_db),
|
||||
async def get_current_user(
|
||||
db: AsyncSession = Depends(get_async_db),
|
||||
token: str = Depends(oauth2_scheme)
|
||||
) -> User:
|
||||
"""
|
||||
@@ -35,7 +36,11 @@ def get_current_user(
|
||||
token_data = get_token_data(token)
|
||||
|
||||
# Get user from database
|
||||
user = db.query(User).filter(User.id == token_data.user_id).first()
|
||||
result = await db.execute(
|
||||
select(User).where(User.id == token_data.user_id)
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
@@ -133,8 +138,8 @@ async def get_optional_token(authorization: str = Header(None)) -> Optional[str]
|
||||
return token
|
||||
|
||||
|
||||
def get_optional_current_user(
|
||||
db: Session = Depends(get_db),
|
||||
async def get_optional_current_user(
|
||||
db: AsyncSession = Depends(get_async_db),
|
||||
token: Optional[str] = Depends(get_optional_token)
|
||||
) -> Optional[User]:
|
||||
"""
|
||||
@@ -153,7 +158,10 @@ def get_optional_current_user(
|
||||
|
||||
try:
|
||||
token_data = get_token_data(token)
|
||||
user = db.query(User).filter(User.id == token_data.user_id).first()
|
||||
result = await db.execute(
|
||||
select(User).where(User.id == token_data.user_id)
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
if not user or not user.is_active:
|
||||
return None
|
||||
return user
|
||||
|
||||
26
backend/app/api/dependencies/permissions.py
Normal file → Executable file
26
backend/app/api/dependencies/permissions.py
Normal file → Executable file
@@ -10,13 +10,13 @@ These dependencies are optional and flexible:
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.database_async import get_async_db
|
||||
from app.models.user import User
|
||||
from app.models.user_organization import OrganizationRole
|
||||
from app.api.dependencies.auth import get_current_user
|
||||
from app.crud.organization import organization as organization_crud
|
||||
from app.crud.organization_async import organization_async as organization_crud
|
||||
|
||||
|
||||
def require_superuser(
|
||||
@@ -73,11 +73,11 @@ class OrganizationPermission:
|
||||
"""
|
||||
self.allowed_roles = allowed_roles
|
||||
|
||||
def __call__(
|
||||
async def __call__(
|
||||
self,
|
||||
organization_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
) -> User:
|
||||
"""
|
||||
Check if user has required role in the organization.
|
||||
@@ -98,7 +98,7 @@ class OrganizationPermission:
|
||||
return current_user
|
||||
|
||||
# Get user's role in organization
|
||||
user_role = organization_crud.get_user_role_in_org(
|
||||
user_role = await organization_crud.get_user_role_in_org(
|
||||
db,
|
||||
user_id=current_user.id,
|
||||
organization_id=organization_id
|
||||
@@ -129,10 +129,10 @@ require_org_member = OrganizationPermission([
|
||||
])
|
||||
|
||||
|
||||
def get_current_org_role(
|
||||
async def get_current_org_role(
|
||||
organization_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
) -> Optional[OrganizationRole]:
|
||||
"""
|
||||
Get the current user's role in an organization.
|
||||
@@ -142,7 +142,7 @@ def get_current_org_role(
|
||||
|
||||
Example:
|
||||
@router.get("/organizations/{org_id}/items")
|
||||
def list_items(
|
||||
async def list_items(
|
||||
org_id: UUID,
|
||||
role: OrganizationRole = Depends(get_current_org_role)
|
||||
):
|
||||
@@ -153,17 +153,17 @@ def get_current_org_role(
|
||||
if current_user.is_superuser:
|
||||
return OrganizationRole.OWNER
|
||||
|
||||
return organization_crud.get_user_role_in_org(
|
||||
return await organization_crud.get_user_role_in_org(
|
||||
db,
|
||||
user_id=current_user.id,
|
||||
organization_id=organization_id
|
||||
)
|
||||
|
||||
|
||||
def require_org_membership(
|
||||
async def require_org_membership(
|
||||
organization_id: UUID,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
) -> User:
|
||||
"""
|
||||
Ensure user is a member of the organization (any role).
|
||||
@@ -173,7 +173,7 @@ def require_org_membership(
|
||||
if current_user.is_superuser:
|
||||
return current_user
|
||||
|
||||
user_role = organization_crud.get_user_role_in_org(
|
||||
user_role = await organization_crud.get_user_role_in_org(
|
||||
db,
|
||||
user_id=current_user.id,
|
||||
organization_id=organization_id
|
||||
|
||||
Reference in New Issue
Block a user