41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
import asyncpg
|
|
import redis.asyncio as redis
|
|
from fastapi import Request, Depends, HTTPException
|
|
import logging
|
|
from .config import get_settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
settings = get_settings()
|
|
|
|
async def get_db_pool(request: Request) -> asyncpg.Pool:
|
|
"""Get database pool from app state"""
|
|
return request.app.state.db_pool
|
|
|
|
async def get_db(request: Request) -> asyncpg.Connection:
|
|
"""Get database connection"""
|
|
pool = await get_db_pool(request)
|
|
async with pool.acquire() as conn:
|
|
yield conn
|
|
|
|
async def get_redis_client(request: Request) -> redis.Redis:
|
|
"""Get Redis client from app state"""
|
|
return request.app.state.redis_client
|
|
|
|
async def get_cache(request: Request):
|
|
"""Get cache service from app state"""
|
|
return request.app.state.cache_service
|
|
|
|
async def verify_bearer_token(request: Request) -> str:
|
|
"""Verify Bearer token for service-to-service authentication
|
|
|
|
Expects header: Authorization: Bearer <token>
|
|
Compares token to settings.API_KEY
|
|
"""
|
|
auth_header = request.headers.get("Authorization", "")
|
|
if not auth_header.startswith("Bearer "):
|
|
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
|
|
token = auth_header.split(" ", 1)[1].strip()
|
|
if token != settings.API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid service token")
|
|
return token
|