from collections import defaultdict import time import os from dotenv import load_dotenv import hashlib load_dotenv() MAX_REQUESTS_PER_HOUR = int(os.getenv("MAX_REQUESTS_PER_HOUR")) user_requests = defaultdict(list) def user_is_limited(hashed_id: str) -> bool: current_time = time.time() # Prune old requests (older than 1 hour) user_requests[hashed_id] = [ ts for ts in user_requests[hashed_id] if current_time - ts < 3600 ] if len(user_requests[hashed_id]) >= MAX_REQUESTS_PER_HOUR: return True user_requests[hashed_id].append(current_time) return False def get_hashed_id(user_id: str) -> str: daily_date = time.strftime("%Y-%m-%d") combined = f"{user_id}{daily_date}" return hashlib.sha256(combined.encode()).hexdigest()[:16]