from fastapi import Depends, HTTPException, Request from config import cfg from core.auth import jwt from core.secrets import get_kid_from_token from db.session import UnitOfWork, get_uow from external.pally import PallyClient from repositories.service_signatures import get_active_signature_by_kid from schemas.dto import AuthContext, ServiceIdentity from services.subscriptions import sync_user_subscription async def get_auth_context( request: Request, uow: UnitOfWork = Depends(get_uow) ) -> AuthContext | None: auth = request.headers.get("Authorization") if not auth: raise HTTPException(status_code=403, detail="No authorization provided.") if auth.startswith("Bearer"): token = auth.removeprefix("Bearer ").strip() ctx = await jwt.authorize(token, uow) await sync_user_subscription(uow.session, user=ctx.user) await uow.commit() return ctx async def get_service_identity( request: Request, uow: UnitOfWork = Depends(get_uow) ) -> ServiceIdentity | None: auth = request.headers.get("Authorization") if not auth: raise HTTPException(401) if auth.startswith("Bearer"): token = auth.removeprefix("Bearer ").strip() kid = get_kid_from_token(token) if not kid: raise HTTPException(401, detail="No kid provided.") signature = await get_active_signature_by_kid(uow.session, kid) if not signature: raise HTTPException(401, detail="Invalid signature") return ServiceIdentity(service=signature.kid) def get_pally_client() -> PallyClient: return PallyClient(api_token=cfg.pally_token, payer_pays_commission=True)