41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
# dependencies.py
|
|
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
|
|
from pydantic import BaseModel
|
|
|
|
# class UserInDB(User):
|
|
# hashed_password: str
|
|
|
|
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_current_user(db: AsyncSession = Depends(get_db), api_key:str = Security(api_key_header)):
|
|
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 db.execute(select(User).filter(User.api_key == api_key))
|
|
user = user.scalars().first()
|
|
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)):
|
|
if current_user.role != UserRole.admin:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions")
|
|
return current_user
|