48 lines
1.6 KiB
Python
48 lines
1.6 KiB
Python
from fastapi import Depends, HTTPException, Request
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from config import cfg
|
|
from core.auth import jwt
|
|
from core.secrets import get_kid_from_token
|
|
from db.session import get_db
|
|
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, session: AsyncSession = Depends(get_db)
|
|
) -> 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, session)
|
|
await sync_user_subscription(session, user=ctx.user)
|
|
await session.commit()
|
|
return ctx
|
|
|
|
|
|
async def get_service_identity(
|
|
request: Request, session: AsyncSession = Depends(get_db)
|
|
) -> ServiceIdentity | None:
|
|
auth = request.headers.get("Authorization")
|
|
|
|
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(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)
|