Mirrored from https://github.com/Camo67/OCIU-npo.git
Synced Nov 21, 06:00 UTC
fix/ociu-remove-placeholder-content
| 1 | from fastapi import Request, HTTPException |
| 2 | from backend.services.redis_cache import redis_cache |
| 3 | |
| 4 | async def subscription_middleware(request: Request, call_next): |
| 5 | # Skip for public endpoints or static assets |
| 6 | if request.url.path.startswith("/api/agent"): |
| 7 | user_id = request.headers.get("X-User-Id", "anonymous") |
| 8 | |
| 9 | # Check subscription state in Redis |
| 10 | sub_state = await redis_cache.get(f"sub:{user_id}") |
| 11 | |
| 12 | # Default for anonymous or new users |
| 13 | if not sub_state: |
| 14 | sub_state = "free" |
| 15 | await redis_cache.set(f"sub:{user_id}", "free") |
| 16 | |
| 17 | # Check usage caps for free tier |
| 18 | usage_count = await redis_cache.get(f"usage:{user_id}") |
| 19 | if not usage_count: |
| 20 | usage_count = "0" |
| 21 | |
| 22 | if sub_state == "free" and int(usage_count) >= 3: |
| 23 | raise HTTPException(status_code=402, detail="Usage limit reached. Please upgrade to Pro.") |
| 24 | |
| 25 | # Increment usage |
| 26 | await redis_cache.set(f"usage:{user_id}", str(int(usage_count) + 1)) |
| 27 | |
| 28 | response = await call_next(request) |
| 29 | return response |