Skip to content

Instantly share code, notes, and snippets.

@aksh-at
Created February 25, 2023 00:27
Show Gist options
  • Save aksh-at/e613b1c1e09022663b8d6ebd7f22268c to your computer and use it in GitHub Desktop.
Save aksh-at/e613b1c1e09022663b8d6ebd7f22268c to your computer and use it in GitHub Desktop.
Modal webhook with bearer token authentication
import modal
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
auth_scheme = HTTPBearer()
stub = modal.Stub(
"example-web-badges",
image=modal.Image.debian_slim().pip_install("pybadges", "pypistats"),
)
@stub.webhook(secret=modal.Secret.from_name("badges-auth-token"))
async def package_downloads(package_name: str, token: HTTPAuthorizationCredentials = Depends(auth_scheme)):
# Authenticate the request
import os
if token.credentials != os.environ["BADGES_AUTH_TOKEN"]:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect bearer token",
headers={"WWW-Authenticate": "Bearer"},
)
# Handler body
import json
import pypistats
from fastapi import Response
from pybadges import badge
stats = json.loads(pypistats.recent(package_name, format="json"))
svg = badge(
left_text=f"{package_name} downloads",
right_text=str(stats["data"]["last_month"]),
right_color="blue",
)
return Response(content=svg, media_type="image/svg+xml")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment