|
| 1 | +import time |
| 2 | +from flask import request, jsonify |
| 3 | +from mind_matter_api.extensions import cache |
| 4 | +from mind_matter_api.utils.auth import decode_auth_token # assume this exists |
| 5 | + |
| 6 | +def get_rate_limit_identity(): |
| 7 | + # 1. Check for Device ID header (mobile apps) |
| 8 | + device_id = request.headers.get("X-Device-ID") |
| 9 | + if device_id: |
| 10 | + return f"device:{device_id}" |
| 11 | + |
| 12 | + # 2. Check for authenticated user (e.g. JWT bearer) |
| 13 | + auth_header = request.headers.get("Authorization") |
| 14 | + if auth_header and " " in auth_header: |
| 15 | + token_type, token = auth_header.split(" ", 1) |
| 16 | + if token_type.lower() == "bearer": |
| 17 | + try: |
| 18 | + user_id = decode_auth_token(token) |
| 19 | + if user_id: |
| 20 | + return f"user:{user_id}" |
| 21 | + except Exception: |
| 22 | + pass |
| 23 | + |
| 24 | + # 3. Fallback to IP address |
| 25 | + return f"ip:{request.remote_addr or 'unknown'}" |
| 26 | + |
| 27 | + |
| 28 | +def rate_limit_middleware(limit: int, window: int, exclude_paths=None, exclude_methods=None): |
| 29 | + exclude_paths = exclude_paths or [] |
| 30 | + exclude_methods = exclude_methods or [] |
| 31 | + |
| 32 | + def middleware(): |
| 33 | + if request.path in exclude_paths or request.method in exclude_methods: |
| 34 | + return |
| 35 | + |
| 36 | + identity = get_rate_limit_identity() |
| 37 | + key = f"rate-limit:{identity}:{request.endpoint}" |
| 38 | + now = time.time() |
| 39 | + |
| 40 | + record = cache.get(key) |
| 41 | + |
| 42 | + if record: |
| 43 | + count, first_time = record |
| 44 | + if now - first_time < window: |
| 45 | + if count >= limit: |
| 46 | + retry_after = int(window - (now - first_time) + 1) |
| 47 | + response = jsonify({ |
| 48 | + "error": "Rate limit exceeded", |
| 49 | + "retry_after_seconds": retry_after |
| 50 | + }) |
| 51 | + response.headers["Retry-After"] = str(retry_after) |
| 52 | + return response, 429 |
| 53 | + cache.set(key, (count + 1, first_time), timeout=window * 2) |
| 54 | + else: |
| 55 | + cache.set(key, (1, now), timeout=window * 2) |
| 56 | + else: |
| 57 | + cache.set(key, (1, now), timeout=window * 2) |
| 58 | + |
| 59 | + return middleware |
0 commit comments