File size: 2,103 Bytes
2d521fd
 
 
 
 
88c664f
2d521fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88c664f
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
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"])

# Rate limiter for registration (5 per hour per IP)
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")

    # 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."
    }


@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,
    }


# ===== DEBUG ENDPOINT – Remove in production =====
@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")
    }