41 lines
1.5 KiB
Python
41 lines
1.5 KiB
Python
"""FastAPI dependencies: DB, current user, admin-only."""
|
|
from __future__ import annotations
|
|
|
|
from typing import AsyncIterator
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.security import decode_access_token
|
|
from app.db import get_db_dep
|
|
from app.models import User
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
|
|
|
|
|
async def get_current_user(
|
|
token: str | None = Depends(oauth2_scheme),
|
|
db: AsyncSession = Depends(get_db_dep),
|
|
) -> User:
|
|
if not token:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="missing_token")
|
|
payload = decode_access_token(token)
|
|
if not payload or payload.get("type") != "access":
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid_token")
|
|
user_id = payload.get("sub")
|
|
if not user_id:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid_token")
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalars().first()
|
|
if not user or not user.is_active:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="user_not_found")
|
|
return user
|
|
|
|
|
|
async def require_admin(user: User = Depends(get_current_user)) -> User:
|
|
if not user.is_admin:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="admin_required")
|
|
return user
|