File size: 1,517 Bytes
56945de
1e9b4a1
 
56945de
 
1e9b4a1
8456fc7
 
1e9b4a1
 
56945de
 
1e9b4a1
 
56945de
 
 
 
 
 
 
 
 
 
 
 
1e9b4a1
 
56945de
8456fc7
 
 
 
 
56945de
 
 
 
 
 
 
1e9b4a1
8456fc7
 
 
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
import os
from typing import Any

import supabase as sb
from fastapi import APIRouter, Header, HTTPException

from middleware.rate_limit import get_usage_daily

router = APIRouter()

SUPABASE_URL = os.environ["SUPABASE_URL"]
SUPABASE_SERVICE_ROLE_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]


def get_supabase() -> sb.Client:
    return sb.create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)


def extract_user_id(token: str, db: sb.Client) -> str:
    try:
        user_response = db.auth.get_user(token)
        return str(user_response.user.id)
    except Exception as e:
        raise HTTPException(status_code=401, detail=f"μœ νš¨ν•˜μ§€ μ•Šμ€ ν† ν°μž…λ‹ˆλ‹€: {e}")


@router.get("/usage")
async def usage(authorization: str = Header(...)) -> dict[str, Any]:
    """
    였늘 **μŠ€μΊ”** 횟수λ₯Ό λ°˜ν™˜ν•œλ‹€.

    μ§‘κ³„λŠ” `usage_daily.scans` ν•˜λ‚˜λ§Œ λ³Έλ‹€(`daily_usage`λŠ” 폐기). 뢄석 μˆ˜λŠ” μ—¬κΈ° μ„žμ§€ μ•ŠλŠ”λ‹€.
    ν•œλ„κ°€ μ—†μ–΄μ‘ŒμœΌλ―€λ‘œ `usage_limit`Β·`remaining`은 μ‘λ‹΅μ—μ„œ 뺐닀 β€” 남은 νšŸμˆ˜λΌλŠ” κ°œλ… μžμ²΄κ°€
    μ—†λ‹€. μˆ«μžλŠ” ν†΅κ³„Β·λ‚¨μš© 좔적 λͺ©μ μœΌλ‘œλ§Œ μ„Όλ‹€.
    """
    if not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Authorization 헀더가 μ˜¬λ°”λ₯΄μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.")
    token = authorization.removeprefix("Bearer ").strip()

    db = get_supabase()
    user_id = extract_user_id(token, db)

    usage_today = get_usage_daily(user_id, db)["scans"]

    return {"usage_today": usage_today}