Add subcription feature

This commit is contained in:
Urtzi Alfaro
2026-01-13 22:22:38 +01:00
parent b931a5c45e
commit 6ddf608d37
61 changed files with 7915 additions and 1238 deletions

View File

@@ -25,7 +25,7 @@ from app.middleware.rate_limiting import APIRateLimitMiddleware
from app.middleware.subscription import SubscriptionMiddleware
from app.middleware.demo_middleware import DemoMiddleware
from app.middleware.read_only_mode import ReadOnlyModeMiddleware
from app.routes import auth, tenant, nominatim, subscription, demo, pos, geocoding, poi_context
from app.routes import auth, tenant, nominatim, subscription, demo, pos, geocoding, poi_context, webhooks
# Initialize logger
logger = structlog.get_logger()
@@ -122,6 +122,9 @@ app.include_router(nominatim.router, prefix="/api/v1/nominatim", tags=["location
app.include_router(geocoding.router, prefix="/api/v1/geocoding", tags=["geocoding"])
app.include_router(pos.router, prefix="/api/v1/pos", tags=["pos"])
app.include_router(demo.router, prefix="/api/v1", tags=["demo"])
app.include_router(webhooks.router, prefix="/api/v1", tags=["webhooks"])
# Also include webhooks at /webhooks prefix to support direct webhook URLs like /webhooks/stripe
app.include_router(webhooks.router, prefix="/webhooks", tags=["webhooks-external"])
# ================================================================

View File

@@ -24,6 +24,11 @@ router = APIRouter()
service_discovery = ServiceDiscovery()
metrics = MetricsCollector("gateway")
# Register custom metrics for auth routes
metrics.register_counter("gateway_auth_requests_total", "Total authentication requests through gateway")
metrics.register_counter("gateway_auth_responses_total", "Total authentication responses from gateway")
metrics.register_counter("gateway_auth_errors_total", "Total authentication errors in gateway")
# Auth service configuration
AUTH_SERVICE_URL = settings.AUTH_SERVICE_URL or "http://auth-service:8000"

View File

@@ -54,6 +54,18 @@ async def proxy_subscription_cancel(request: Request):
target_path = "/api/v1/subscriptions/cancel"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/create-for-registration", methods=["POST", "OPTIONS"])
async def proxy_create_for_registration(request: Request):
"""Proxy create-for-registration request to tenant service"""
target_path = "/api/v1/subscriptions/create-for-registration"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/payment-customers/create", methods=["POST", "OPTIONS"])
async def proxy_payment_customer_create(request: Request):
"""Proxy payment customer creation request to tenant service"""
target_path = "/api/v1/payment-customers/create"
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/reactivate", methods=["POST", "OPTIONS"])
async def proxy_subscription_reactivate(request: Request):
"""Proxy subscription reactivation request to tenant service"""

View File

@@ -0,0 +1,107 @@
"""
Webhook routes for API Gateway - Handles webhook endpoints
"""
from fastapi import APIRouter, Request, Response
from fastapi.responses import JSONResponse
import httpx
import logging
from typing import Optional
from app.core.config import settings
from app.core.header_manager import header_manager
logger = logging.getLogger(__name__)
router = APIRouter()
# ================================================================
# WEBHOOK ENDPOINTS - Direct routing to tenant service
# ================================================================
@router.post("/stripe")
async def proxy_stripe_webhook(request: Request):
"""Proxy Stripe webhook requests to tenant service"""
return await _proxy_to_tenant_service(request, "/webhooks/stripe")
@router.post("/generic")
async def proxy_generic_webhook(request: Request):
"""Proxy generic webhook requests to tenant service"""
return await _proxy_to_tenant_service(request, "/webhooks/generic")
# ================================================================
# PROXY HELPER FUNCTIONS
# ================================================================
async def _proxy_to_tenant_service(request: Request, target_path: str):
"""Proxy request to tenant service"""
return await _proxy_request(request, target_path, settings.TENANT_SERVICE_URL)
async def _proxy_request(request: Request, target_path: str, service_url: str):
"""Generic proxy function with enhanced error handling"""
# Handle OPTIONS requests directly for CORS
if request.method == "OPTIONS":
return Response(
status_code=200,
headers={
"Access-Control-Allow-Origin": settings.CORS_ORIGINS_LIST,
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID, Stripe-Signature",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Max-Age": "86400"
}
)
try:
url = f"{service_url}{target_path}"
# Use unified HeaderManager for consistent header forwarding
headers = header_manager.get_all_headers_for_proxy(request)
# Debug logging
logger.info(f"Forwarding webhook request to {url}")
# Get request body if present
body = None
if request.method in ["POST", "PUT", "PATCH"]:
body = await request.body()
# Add query parameters
params = dict(request.query_params)
timeout_config = httpx.Timeout(
connect=30.0,
read=60.0,
write=30.0,
pool=30.0
)
async with httpx.AsyncClient(timeout=timeout_config) as client:
response = await client.request(
method=request.method,
url=url,
headers=headers,
content=body,
params=params
)
# Handle different response types
if response.headers.get("content-type", "").startswith("application/json"):
try:
content = response.json()
except:
content = {"message": "Invalid JSON response from service"}
else:
content = response.text
return JSONResponse(
status_code=response.status_code,
content=content
)
except Exception as e:
logger.error(f"Unexpected error proxying webhook request to {service_url}{target_path}: {e}")
raise HTTPException(
status_code=500,
detail="Internal gateway error"
)