""" MIT License Copyright (c) 2025 Hopsenn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from functools import wraps from django.core.cache import cache from django.http import JsonResponse from .validators import verify_token from .settings import GENERATE_URL, PUBLIC_KEY def get_builtin_key_func(name): if name == 'ip': return lambda request: request.META.get('REMOTE_ADDR', 'unknown-ip') raise ValueError(f"Unknown built-in key: '{name}'") def hoptcha_protected(threshold=5, timeout=300, key='ip'): """ Decorator that applies CAPTCHA verification after `threshold` failed attempts, tracked via cache using a customizable key. The `key` can be: - a string like 'ip' to use a built-in method - a callable that accepts a Django request and returns a string """ key_func = get_builtin_key_func(key) if isinstance(key, str) else key def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): key_val = key_func(request) cache_key = f"hoptcha-attempts:{key_val}" attempts = cache.get(cache_key, 0) if attempts >= threshold: token = request.POST.get("captcha_token") or request.GET.get("captcha_token") if not token or not verify_token(token): return JsonResponse({ "error": "CAPTCHA", "url": GENERATE_URL, "key": PUBLIC_KEY }, status=400) cache.set(cache_key, attempts + 1, timeout=timeout) return view_func(request, *args, **kwargs) return _wrapped_view return decorator