Files
db-middleware/core/dependencies.py

41 lines
1.5 KiB
Python

from fastapi import Depends, HTTPException, status, Security
from fastapi.security import APIKeyHeader
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from data.db import SessionLocal
from data.models import User, UserRole
async def get_db():
async with SessionLocal() as session:
yield session
API_KEY_NAME = "Authorization"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
async def get_user_from_api_key(db:AsyncSession, api_key:str):
user = await db.execute(select(User).filter(User.api_key == api_key))
user = user.scalars().first()
return user
async def get_current_user(db: AsyncSession = Depends(get_db), api_key:str = Security(api_key_header)) -> User:
if api_key_header is None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="API key missing"
)
if not api_key:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="API key missing, provide it in the header value [Authorization]"
)
user= await get_user_from_api_key(db=db, api_key=api_key)
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
return user
async def get_admin_user(current_user: User = Depends(get_current_user)) -> User:
if current_user.role != UserRole.admin:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions")
return current_user