api/routers/tlsync.py

45 lines
1.5 KiB
Python

import os
from typing import Dict
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from modules.auth.supabase_bearer import verify_supabase_jwt_str
router = APIRouter()
security = HTTPBearer(auto_error=False)
async def require_supabase_user(
credentials: HTTPAuthorizationCredentials | None = Depends(security),
) -> Dict:
"""Validate a Supabase bearer token and return the decoded session claims."""
if credentials is None or not credentials.credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
try:
return verify_supabase_jwt_str(credentials.credentials)
except HTTPException as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=exc.detail,
headers={"WWW-Authenticate": "Bearer"},
) from exc
@router.get("/token")
async def get_tlsync_token(_claims: Dict = Depends(require_supabase_user)) -> Dict[str, str]:
"""Return the API-side TLSync shared secret for authenticated clients."""
tlsync_secret = os.getenv("TLSYNC_SECRET")
if not tlsync_secret:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="TLSync secret is not configured",
)
return {"token": tlsync_secret}