61 lines
2.4 KiB
Python
61 lines
2.4 KiB
Python
"""
|
|
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 default_key_func(request):
|
|
return request.META.get('REMOTE_ADDR', 'unknown-ip')
|
|
|
|
def hoptcha_required(threshold=5, timeout=300, key_func=default_key_func):
|
|
"""
|
|
Decorator that applies CAPTCHA verification after `threshold` failed attempts,
|
|
tracked via cache using a customizable `key_func`.
|
|
"""
|
|
|
|
def decorator(view_func):
|
|
@wraps(view_func)
|
|
def _wrapped_view(request, *args, **kwargs):
|
|
key = key_func(request)
|
|
cache_key = f"hoptcha-attempts:{key}"
|
|
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)
|
|
|
|
# Increment and store attempt count unless the view says otherwise
|
|
cache.set(cache_key, attempts + 1, timeout=timeout)
|
|
return view_func(request, *args, **kwargs)
|
|
return _wrapped_view
|
|
return decorator
|