30 lines
990 B
Python
30 lines
990 B
Python
from fastapi import Depends, HTTPException, Security, status
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from proxy_pool.accounts.models import User
|
|
from proxy_pool.accounts.service import verify_api_key
|
|
from proxy_pool.common.dependencies import get_db
|
|
|
|
security = HTTPBearer()
|
|
|
|
|
|
async def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Security(security),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> User:
|
|
"""FastAPI dependency that resolves an API key to a User.
|
|
|
|
Usage in routes:
|
|
@router.get("/something")
|
|
async def something(user: User = Depends(get_current_user)):
|
|
"""
|
|
user = await verify_api_key(db, credentials.credentials)
|
|
if user is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired API key",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
return user
|