Release Candidate: Production Release with Multi-Tenant & Onboarding Enhancements
This commit is contained in:
@@ -12,7 +12,10 @@ from .routes import (
|
||||
alerts,
|
||||
dashboard,
|
||||
logs,
|
||||
preflight
|
||||
preflight,
|
||||
payment,
|
||||
disputes,
|
||||
fraud_warnings,
|
||||
)
|
||||
|
||||
# Create main router
|
||||
@@ -26,5 +29,8 @@ router.include_router(alerts.router, tags=["subscription"])
|
||||
router.include_router(dashboard.router, tags=["subscription"])
|
||||
router.include_router(logs.router, tags=["subscription"])
|
||||
router.include_router(preflight.router, tags=["subscription"])
|
||||
router.include_router(payment.router, tags=["subscription"])
|
||||
router.include_router(disputes.router, tags=["subscription"])
|
||||
router.include_router(fraud_warnings.router, tags=["subscription"])
|
||||
|
||||
__all__ = ["router"]
|
||||
|
||||
@@ -3,6 +3,6 @@ Subscription API Routes
|
||||
All route modules are imported here for easy access.
|
||||
"""
|
||||
|
||||
from . import usage, plans, subscriptions, alerts, dashboard, logs, preflight
|
||||
from . import usage, plans, subscriptions, alerts, dashboard, logs, preflight, payment, disputes
|
||||
|
||||
__all__ = ["usage", "plans", "subscriptions", "alerts", "dashboard", "logs", "preflight"]
|
||||
__all__ = ["usage", "plans", "subscriptions", "alerts", "dashboard", "logs", "preflight", "payment", "disputes"]
|
||||
|
||||
142
backend/api/subscription/routes/disputes.py
Normal file
142
backend/api/subscription/routes/disputes.py
Normal file
@@ -0,0 +1,142 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Dict, Any, Optional
|
||||
from pydantic import BaseModel
|
||||
from services.database import get_db
|
||||
from middleware.auth_middleware import get_current_user
|
||||
from loguru import logger
|
||||
import stripe
|
||||
import os
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _ensure_admin(current_user: Dict[str, Any]) -> None:
|
||||
disable_auth = os.getenv("DISABLE_AUTH", "false").lower() == "true"
|
||||
if disable_auth:
|
||||
return
|
||||
|
||||
email = (current_user.get("email") or "").lower()
|
||||
role = None
|
||||
public_metadata = current_user.get("public_metadata")
|
||||
if isinstance(public_metadata, dict):
|
||||
role = public_metadata.get("role") or current_user.get("role")
|
||||
else:
|
||||
role = current_user.get("role")
|
||||
|
||||
admin_emails_raw = os.getenv("ADMIN_EMAILS", "")
|
||||
admin_emails = {
|
||||
e.strip().lower() for e in admin_emails_raw.split(",") if e.strip()
|
||||
}
|
||||
admin_domain = (os.getenv("ADMIN_EMAIL_DOMAIN") or "").lower().strip()
|
||||
|
||||
is_admin_email = email and email in admin_emails
|
||||
is_admin_domain = email and admin_domain and email.endswith("@" + admin_domain)
|
||||
is_admin_role = role == "admin"
|
||||
|
||||
if not (is_admin_email or is_admin_domain or is_admin_role):
|
||||
raise HTTPException(status_code=403, detail="Admin access required for dispute operations")
|
||||
|
||||
|
||||
def _get_stripe_client() -> None:
|
||||
api_key = os.getenv("STRIPE_SECRET_KEY")
|
||||
if not api_key:
|
||||
logger.error("STRIPE_SECRET_KEY is not configured; dispute operations are disabled")
|
||||
raise HTTPException(status_code=500, detail="Payment service not configured")
|
||||
stripe.api_key = api_key
|
||||
|
||||
|
||||
class DisputeEvidenceUpdateRequest(BaseModel):
|
||||
evidence: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
@router.get("/disputes")
|
||||
async def list_disputes(
|
||||
limit: int = 10,
|
||||
starting_after: Optional[str] = None,
|
||||
ending_before: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_get_stripe_client()
|
||||
_ensure_admin(current_user)
|
||||
|
||||
try:
|
||||
params: Dict[str, Any] = {"limit": max(1, min(limit, 100))}
|
||||
if starting_after:
|
||||
params["starting_after"] = starting_after
|
||||
if ending_before:
|
||||
params["ending_before"] = ending_before
|
||||
|
||||
disputes = stripe.Dispute.list(**params)
|
||||
return {"data": disputes}
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing disputes: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to list disputes")
|
||||
|
||||
|
||||
@router.get("/disputes/{dispute_id}")
|
||||
async def get_dispute(
|
||||
dispute_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_get_stripe_client()
|
||||
_ensure_admin(current_user)
|
||||
|
||||
try:
|
||||
dispute = stripe.Dispute.retrieve(dispute_id)
|
||||
return {"data": dispute}
|
||||
except stripe.error.InvalidRequestError as e:
|
||||
logger.warning(f"Invalid dispute id {dispute_id}: {e}")
|
||||
raise HTTPException(status_code=404, detail="Dispute not found")
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrieving dispute {dispute_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to retrieve dispute")
|
||||
|
||||
|
||||
@router.post("/disputes/{dispute_id}")
|
||||
async def update_dispute(
|
||||
dispute_id: str,
|
||||
payload: DisputeEvidenceUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_get_stripe_client()
|
||||
_ensure_admin(current_user)
|
||||
|
||||
if not payload.evidence:
|
||||
raise HTTPException(status_code=400, detail="Evidence payload is required to update a dispute")
|
||||
|
||||
try:
|
||||
dispute = stripe.Dispute.modify(
|
||||
dispute_id,
|
||||
evidence=payload.evidence,
|
||||
)
|
||||
return {"data": dispute}
|
||||
except stripe.error.InvalidRequestError as e:
|
||||
logger.warning(f"Invalid dispute id {dispute_id} during update: {e}")
|
||||
raise HTTPException(status_code=404, detail="Dispute not found")
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating dispute {dispute_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to update dispute")
|
||||
|
||||
|
||||
@router.post("/disputes/{dispute_id}/close")
|
||||
async def close_dispute(
|
||||
dispute_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_get_stripe_client()
|
||||
_ensure_admin(current_user)
|
||||
|
||||
try:
|
||||
dispute = stripe.Dispute.close(dispute_id)
|
||||
return {"data": dispute}
|
||||
except stripe.error.InvalidRequestError as e:
|
||||
logger.warning(f"Invalid dispute id {dispute_id} during close: {e}")
|
||||
raise HTTPException(status_code=404, detail="Dispute not found")
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing dispute {dispute_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to close dispute")
|
||||
209
backend/api/subscription/routes/fraud_warnings.py
Normal file
209
backend/api/subscription/routes/fraud_warnings.py
Normal file
@@ -0,0 +1,209 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Dict, Any, Optional
|
||||
from pydantic import BaseModel
|
||||
from services.database import get_db
|
||||
from middleware.auth_middleware import get_current_user
|
||||
from loguru import logger
|
||||
import stripe
|
||||
import os
|
||||
from datetime import datetime
|
||||
from models.subscription_models import FraudWarning
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _ensure_admin(current_user: Dict[str, Any]) -> None:
|
||||
disable_auth = os.getenv("DISABLE_AUTH", "false").lower() == "true"
|
||||
if disable_auth:
|
||||
return
|
||||
|
||||
email = (current_user.get("email") or "").lower()
|
||||
role = None
|
||||
public_metadata = current_user.get("public_metadata")
|
||||
if isinstance(public_metadata, dict):
|
||||
role = public_metadata.get("role") or current_user.get("role")
|
||||
else:
|
||||
role = current_user.get("role")
|
||||
|
||||
admin_emails_raw = os.getenv("ADMIN_EMAILS", "")
|
||||
admin_emails = {
|
||||
e.strip().lower() for e in admin_emails_raw.split(",") if e.strip()
|
||||
}
|
||||
admin_domain = (os.getenv("ADMIN_EMAIL_DOMAIN") or "").lower().strip()
|
||||
|
||||
is_admin_email = email and email in admin_emails
|
||||
is_admin_domain = email and admin_domain and email.endswith("@" + admin_domain)
|
||||
is_admin_role = role == "admin"
|
||||
|
||||
if not (is_admin_email or is_admin_domain or is_admin_role):
|
||||
raise HTTPException(status_code=403, detail="Admin access required for fraud warning operations")
|
||||
|
||||
|
||||
def _get_stripe_client() -> None:
|
||||
api_key = os.getenv("STRIPE_SECRET_KEY")
|
||||
if not api_key:
|
||||
logger.error("STRIPE_SECRET_KEY is not configured; fraud warning operations are disabled")
|
||||
raise HTTPException(status_code=500, detail="Payment service not configured")
|
||||
stripe.api_key = api_key
|
||||
|
||||
|
||||
class FraudWarningRefundRequest(BaseModel):
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
class FraudWarningIgnoreRequest(BaseModel):
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/fraud-warnings")
|
||||
async def list_fraud_warnings(
|
||||
status: Optional[str] = "open",
|
||||
limit: int = 20,
|
||||
offset: int = 0,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_ensure_admin(current_user)
|
||||
|
||||
query = db.query(FraudWarning)
|
||||
if status:
|
||||
query = query.filter(FraudWarning.status == status)
|
||||
|
||||
limit = max(1, min(limit, 100))
|
||||
items = (
|
||||
query.order_by(FraudWarning.created_at.desc())
|
||||
.offset(max(0, offset))
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
data = []
|
||||
for fw in items:
|
||||
data.append(
|
||||
{
|
||||
"id": fw.id,
|
||||
"charge_id": fw.charge_id,
|
||||
"payment_intent_id": fw.payment_intent_id,
|
||||
"user_id": fw.user_id,
|
||||
"amount": fw.amount,
|
||||
"currency": fw.currency,
|
||||
"status": fw.status,
|
||||
"action": fw.action,
|
||||
"action_at": fw.action_at.isoformat() if fw.action_at else None,
|
||||
"created_at": fw.created_at.isoformat() if fw.created_at else None,
|
||||
}
|
||||
)
|
||||
|
||||
return {"data": data}
|
||||
|
||||
|
||||
@router.get("/fraud-warnings/{warning_id}")
|
||||
async def get_fraud_warning(
|
||||
warning_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_ensure_admin(current_user)
|
||||
|
||||
fw = db.query(FraudWarning).filter(FraudWarning.id == warning_id).first()
|
||||
if not fw:
|
||||
raise HTTPException(status_code=404, detail="Fraud warning not found")
|
||||
|
||||
payload: Dict[str, Any] = {
|
||||
"id": fw.id,
|
||||
"charge_id": fw.charge_id,
|
||||
"payment_intent_id": fw.payment_intent_id,
|
||||
"user_id": fw.user_id,
|
||||
"amount": fw.amount,
|
||||
"currency": fw.currency,
|
||||
"status": fw.status,
|
||||
"action": fw.action,
|
||||
"action_at": fw.action_at.isoformat() if fw.action_at else None,
|
||||
"reason_notes": fw.reason_notes,
|
||||
"created_at": fw.created_at.isoformat() if fw.created_at else None,
|
||||
"meta_info": fw.meta_info,
|
||||
}
|
||||
|
||||
return {"data": payload}
|
||||
|
||||
|
||||
@router.post("/fraud-warnings/{warning_id}/refund")
|
||||
async def refund_fraud_warning(
|
||||
warning_id: str,
|
||||
payload: FraudWarningRefundRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_ensure_admin(current_user)
|
||||
_get_stripe_client()
|
||||
|
||||
fw = db.query(FraudWarning).filter(FraudWarning.id == warning_id).first()
|
||||
if not fw:
|
||||
raise HTTPException(status_code=404, detail="Fraud warning not found")
|
||||
|
||||
if fw.status == "refunded":
|
||||
raise HTTPException(status_code=400, detail="Fraud warning already refunded")
|
||||
|
||||
try:
|
||||
stripe.Refund.create(charge=fw.charge_id)
|
||||
except stripe.error.InvalidRequestError as e:
|
||||
logger.warning(f"Refund failed for fraud warning {warning_id}, charge {fw.charge_id}: {e}")
|
||||
raise HTTPException(status_code=400, detail="Refund failed for this charge")
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error refunding fraud warning {warning_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Unexpected error while processing refund")
|
||||
|
||||
fw.status = "refunded"
|
||||
fw.action = "refund_full"
|
||||
fw.action_at = datetime.utcnow()
|
||||
if payload and payload.notes:
|
||||
fw.reason_notes = payload.notes
|
||||
|
||||
db.commit()
|
||||
db.refresh(fw)
|
||||
|
||||
return {
|
||||
"data": {
|
||||
"id": fw.id,
|
||||
"status": fw.status,
|
||||
"action": fw.action,
|
||||
"action_at": fw.action_at.isoformat() if fw.action_at else None,
|
||||
"reason_notes": fw.reason_notes,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/fraud-warnings/{warning_id}/ignore")
|
||||
async def ignore_fraud_warning(
|
||||
warning_id: str,
|
||||
payload: FraudWarningIgnoreRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
):
|
||||
_ensure_admin(current_user)
|
||||
|
||||
fw = db.query(FraudWarning).filter(FraudWarning.id == warning_id).first()
|
||||
if not fw:
|
||||
raise HTTPException(status_code=404, detail="Fraud warning not found")
|
||||
|
||||
fw.status = "ignored"
|
||||
fw.action = "ignored"
|
||||
fw.action_at = datetime.utcnow()
|
||||
if payload and payload.notes:
|
||||
fw.reason_notes = payload.notes
|
||||
|
||||
db.commit()
|
||||
db.refresh(fw)
|
||||
|
||||
return {
|
||||
"data": {
|
||||
"id": fw.id,
|
||||
"status": fw.status,
|
||||
"action": fw.action,
|
||||
"action_at": fw.action_at.isoformat() if fw.action_at else None,
|
||||
"reason_notes": fw.reason_notes,
|
||||
}
|
||||
}
|
||||
|
||||
125
backend/api/subscription/routes/payment.py
Normal file
125
backend/api/subscription/routes/payment.py
Normal file
@@ -0,0 +1,125 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Header, BackgroundTasks
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Dict, Any, Optional
|
||||
from pydantic import BaseModel
|
||||
from services.database import get_db
|
||||
from services.subscription.stripe_service import StripeService
|
||||
from middleware.auth_middleware import get_current_user
|
||||
from loguru import logger
|
||||
from models.subscription_models import SubscriptionTier, BillingCycle
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class CreateCheckoutSessionRequest(BaseModel):
|
||||
tier: SubscriptionTier
|
||||
billing_cycle: BillingCycle
|
||||
success_url: str
|
||||
cancel_url: str
|
||||
|
||||
class CreatePortalSessionRequest(BaseModel):
|
||||
return_url: str
|
||||
|
||||
|
||||
_checkout_rate_limit_window_seconds = 60
|
||||
_checkout_rate_limit_max_requests = 10
|
||||
_checkout_attempts_by_user: Dict[str, Any] = defaultdict(list)
|
||||
|
||||
@router.post("/create-checkout-session")
|
||||
async def create_checkout_session(
|
||||
payload: CreateCheckoutSessionRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user),
|
||||
request: Request = None
|
||||
):
|
||||
"""
|
||||
Create a Stripe Checkout Session for subscription.
|
||||
"""
|
||||
user_id = current_user.get("sub") or current_user.get("id")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="User not authenticated")
|
||||
|
||||
now = time.time()
|
||||
attempts = _checkout_attempts_by_user[user_id]
|
||||
window_start = now - _checkout_rate_limit_window_seconds
|
||||
attempts[:] = [ts for ts in attempts if ts >= window_start]
|
||||
attempts.append(now)
|
||||
_checkout_attempts_by_user[user_id] = attempts
|
||||
if len(attempts) > _checkout_rate_limit_max_requests:
|
||||
client_ip = request.client.host if request and request.client else "unknown"
|
||||
logger.warning(f"Checkout rate limit exceeded for user_id={user_id}, ip={client_ip}, attempts={len(attempts)} in { _checkout_rate_limit_window_seconds }s")
|
||||
raise HTTPException(status_code=429, detail="Too many checkout attempts. Please try again shortly.")
|
||||
|
||||
user_email = current_user.get("email")
|
||||
|
||||
stripe_service = StripeService(db)
|
||||
|
||||
try:
|
||||
url = stripe_service.create_checkout_session(
|
||||
user_id=user_id,
|
||||
tier=payload.tier,
|
||||
billing_cycle=payload.billing_cycle,
|
||||
success_url=payload.success_url,
|
||||
cancel_url=payload.cancel_url,
|
||||
user_email=user_email
|
||||
)
|
||||
return {"url": url}
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating checkout session: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to initiate checkout")
|
||||
|
||||
@router.post("/create-portal-session")
|
||||
async def create_portal_session(
|
||||
payload: CreatePortalSessionRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""
|
||||
Create a Stripe Customer Portal session for managing billing.
|
||||
"""
|
||||
user_id = current_user.get("sub") or current_user.get("id")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="User not authenticated")
|
||||
|
||||
stripe_service = StripeService(db)
|
||||
|
||||
try:
|
||||
url = stripe_service.create_portal_session(
|
||||
user_id=user_id,
|
||||
return_url=payload.return_url
|
||||
)
|
||||
return {"url": url}
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating portal session: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to access billing portal")
|
||||
|
||||
@router.post("/webhook")
|
||||
async def stripe_webhook(
|
||||
request: Request,
|
||||
stripe_signature: str = Header(None),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Handle Stripe webhooks.
|
||||
"""
|
||||
if not stripe_signature:
|
||||
raise HTTPException(status_code=400, detail="Missing stripe-signature header")
|
||||
|
||||
payload = await request.body()
|
||||
stripe_service = StripeService(db)
|
||||
|
||||
try:
|
||||
# We need to run this potentially in background or await it
|
||||
# Since it's async, we can await it directly.
|
||||
await stripe_service.handle_webhook(payload, stripe_signature)
|
||||
return {"status": "success"}
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing webhook: {e}")
|
||||
raise HTTPException(status_code=500, detail="Webhook processing failed")
|
||||
Reference in New Issue
Block a user