| """ |
| User endpoints – registration and quota information. |
| """ |
|
|
| import uuid |
| import os |
| 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"]) |
|
|
| |
| limiter = Limiter(key_func=get_remote_address, default_limits=["5/hour"]) |
|
|
|
|
| @router.post("/register") |
| @limiter.limit("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") |
|
|
| |
| new_key = f"sk_free_{uuid.uuid4().hex[:24]}" |
|
|
| |
| 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." |
| } |
|
|
|
|
| @router.get("/quota") |
| 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, |
| } |
|
|
|
|
| |
| @router.get("/tracker-status") |
| async def tracker_status(): |
| """ |
| Debug endpoint to check if the usage tracker is initialised. |
| Returns the tracker object and environment variables. |
| """ |
| return { |
| "tracker": str(tracker), |
| "env_tracking": os.getenv("ARF_USAGE_TRACKING"), |
| "env_db_path": os.getenv("ARF_USAGE_DB_PATH") |
| } |