30 lines
1.1 KiB
Python
30 lines
1.1 KiB
Python
from typing import AsyncGenerator
|
|
|
|
from fastapi import Depends, HTTPException, Request, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.user import User
|
|
from app.services.auth import get_user_by_id
|
|
from app.services.database import AsyncSessionLocal
|
|
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
async with AsyncSessionLocal() as session:
|
|
async with session.begin():
|
|
yield session
|
|
|
|
|
|
async def get_current_user(request: Request, db: AsyncSession = Depends(get_db)) -> User:
|
|
user_id = getattr(request.state, "user_id", None)
|
|
if user_id is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
|
user = await get_user_by_id(db, user_id)
|
|
if user is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or inactive")
|
|
return user
|
|
|
|
|
|
async def require_admin(current_user: User = Depends(get_current_user)) -> User:
|
|
if current_user.role != "admin":
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
|
return current_user
|