Files
thrillwiki_django_no_react/backend/apps/accounts/mixins.py

46 lines
1.4 KiB
Python

"""
Mixins for authentication views.
"""
from django.core.exceptions import ValidationError
from apps.core.utils.turnstile import get_client_ip, validate_turnstile_token
class TurnstileMixin:
"""
Mixin to handle Cloudflare Turnstile validation.
Works with both form POST data and JSON request bodies.
"""
def validate_turnstile(self, request):
"""
Validate the Turnstile response token.
The token can be provided as:
- 'cf-turnstile-response' in POST data (form submission)
- 'turnstile_token' in JSON body (API request)
"""
# Try to get token from various sources
token = None
# Check POST data (form submissions)
if hasattr(request, "POST"):
token = request.POST.get("cf-turnstile-response")
# Check JSON body (API requests)
if not token and hasattr(request, "data"):
data = getattr(request, "data", {})
if hasattr(data, "get"):
token = data.get("turnstile_token") or data.get("cf-turnstile-response")
# Get client IP
ip = get_client_ip(request)
# Validate the token
result = validate_turnstile_token(token, ip)
if not result.get("success"):
error_msg = result.get("error", "Captcha verification failed. Please try again.")
raise ValidationError(error_msg)