|
| 1 | +from fastapi import APIRouter, Request, Header, BackgroundTasks |
| 2 | +from packages.config.settings import Settings |
| 3 | +from packages.app_store.github.utils import verify_github_signature, SignatureVerificationError |
| 4 | +from packages.app_store.github.webhook import handle_github_event, run_ingestion |
| 5 | +from apps.api.utils.response import APIResponse |
| 6 | +from apps.api.utils.exceptions import BadRequestException, UnauthorizedException |
| 7 | +import logging |
| 8 | + |
| 9 | +router = APIRouter(prefix="/integrations", tags=["Integrations"]) |
| 10 | +settings = Settings() |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +@router.post("/github/webhook") |
| 14 | +async def github_webhook( |
| 15 | + request: Request, |
| 16 | + background_tasks: BackgroundTasks, |
| 17 | + x_github_event: str = Header(None) |
| 18 | +): |
| 19 | + """ |
| 20 | + Handle GitHub Webhooks. |
| 21 | + """ |
| 22 | + if not x_github_event: |
| 23 | + raise BadRequestException(message="Missing X-GitHub-Event header") |
| 24 | + |
| 25 | + # Always verify signature in production |
| 26 | + try: |
| 27 | + await verify_github_signature(request, settings.GITHUB_WEBHOOK_SECRET) |
| 28 | + except SignatureVerificationError as e: |
| 29 | + logger.warning(f"GitHub signature verification failed: {str(e)}") |
| 30 | + raise UnauthorizedException(message=str(e)) |
| 31 | + |
| 32 | + payload = await request.json() |
| 33 | + |
| 34 | + result = handle_github_event(x_github_event, payload) |
| 35 | + |
| 36 | + if result.get("status") == "triggered" and result.get("task") == "ingest": |
| 37 | + repo_url = result.get("repo_url") |
| 38 | + branch = result.get("branch") |
| 39 | + if repo_url: |
| 40 | + background_tasks.add_task(run_ingestion, repo_url, branch) |
| 41 | + return APIResponse.success( |
| 42 | + message=f"Ingestion triggered for {repo_url} on {branch}", |
| 43 | + data={"status": "accepted", "repo_url": repo_url, "branch": branch} |
| 44 | + ) |
| 45 | + |
| 46 | + return APIResponse.success( |
| 47 | + message="Webhook processed", |
| 48 | + data=result |
| 49 | + ) |
0 commit comments