44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
from typing import AsyncGenerator
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
|
|
from app.database import AsyncSessionLocal
|
|
from app.utils.security import decode_token
|
|
|
|
bearer_scheme = HTTPBearer()
|
|
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
async with AsyncSessionLocal() as session:
|
|
yield session
|
|
|
|
|
|
async def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
from app.models.user import User
|
|
|
|
token = credentials.credentials
|
|
user_id = decode_token(token)
|
|
if user_id is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
|
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
if user is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
if user.is_disabled:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
|
|
|
|
return user
|
|
|
|
|
|
async def get_current_admin(current_user=Depends(get_current_user)):
|
|
if not current_user.is_admin:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
|
return current_user
|