feat: add API key auth dependency
This commit is contained in:
parent
9fd298235e
commit
2aa3a61ed4
@ -53,7 +53,7 @@ extend-exclude = ["alembic", "tests"]
|
||||
select = ["E", "F", "I", "N", "UP", "B", "A", "SIM"]
|
||||
|
||||
[tool.ruff.lint.flake8-bugbear]
|
||||
extend-immutable-calls = ["Depends", "fastapi.Depends", "Query", "fastapi.Query"]
|
||||
extend-immutable-calls = ["Depends", "fastapi.Depends", "Query", "fastapi.Query", "Security", "fastapi.Security"]
|
||||
|
||||
[tool.mypy]
|
||||
plugins = ["pydantic.mypy"]
|
||||
|
||||
29
src/proxy_pool/accounts/auth.py
Normal file
29
src/proxy_pool/accounts/auth.py
Normal file
@ -0,0 +1,29 @@
|
||||
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
|
||||
Loading…
x
Reference in New Issue
Block a user