Spaces:
Build error
Build error
| """ | |
| User endpoints – registration and quota information. | |
| """ | |
| import uuid | |
| from fastapi import APIRouter, Depends, HTTPException, Request | |
| from slowapi import Limiter | |
| from slowapi.util import get_remote_address | |
| from app.core.usage_tracker import tracker, enforce_quota, Tier | |
| router = APIRouter(prefix="/users", tags=["users"]) | |
| # Rate limiter for registration (5 per hour per IP) | |
| limiter = Limiter(key_func=get_remote_address, default_limits=["5/hour"]) | |
| async def register_user(request: Request): | |
| """ | |
| Public endpoint to create a new free‑tier API key. | |
| Rate‑limited to 5 requests per hour per IP address. | |
| """ | |
| if tracker is None: | |
| raise HTTPException( | |
| status_code=503, | |
| detail="Usage tracking not available") | |
| # Generate a new API key | |
| new_key = f"sk_free_{uuid.uuid4().hex[:24]}" | |
| # Store it as FREE tier | |
| success = tracker.get_or_create_api_key(new_key, Tier.FREE) | |
| if not success: | |
| raise HTTPException(status_code=500, detail="Failed to create API key") | |
| return { | |
| "api_key": new_key, | |
| "tier": "free", | |
| "message": "API key created. Store it securely – you won't see it again."} | |
| async def get_user_quota( | |
| request: Request, | |
| quota: dict = Depends(enforce_quota)): | |
| """ | |
| Return the current user's tier and remaining evaluation quota. | |
| Requires API key in Authorization header. | |
| """ | |
| tier = quota["tier"] | |
| remaining = quota["remaining"] | |
| limit = tier.monthly_evaluation_limit if tier else None | |
| return { | |
| "tier": tier.value, | |
| "remaining": remaining, | |
| "limit": limit, | |
| } | |