41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
"""
|
|
Authentication decorators for FastAPI
|
|
"""
|
|
|
|
from functools import wraps
|
|
from fastapi import HTTPException, Depends
|
|
from fastapi.security import HTTPBearer
|
|
import httpx
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
security = HTTPBearer()
|
|
|
|
def verify_service_token(auth_service_url: str):
|
|
"""Verify service token with auth service"""
|
|
|
|
async def verify_token(token: str = Depends(security)):
|
|
try:
|
|
async with httpx.AsyncClient() as client:
|
|
response = await client.post(
|
|
f"{auth_service_url}/verify",
|
|
headers={"Authorization": f"Bearer {token.credentials}"}
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
return response.json()
|
|
else:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="Invalid authentication credentials"
|
|
)
|
|
|
|
except httpx.RequestError as e:
|
|
logger.error(f"Auth service unavailable: {e}")
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail="Authentication service unavailable"
|
|
)
|
|
|
|
return verify_token |