|
9 | 9 |
|
10 | 10 | from django import forms |
11 | 11 | from django.forms.widgets import HiddenInput |
12 | | -from django.http import JsonResponse |
13 | 12 | from django.utils.translation import gettext_lazy as _ |
14 | | -from django.views.decorators.http import require_GET |
15 | 13 |
|
16 | 14 | # TODO: Add as a dependency |
17 | 15 | import altcha |
@@ -90,8 +88,31 @@ class AltchaField(forms.Field): |
90 | 88 | "required": _("Altcha CAPTCHA token is missing."), |
91 | 89 | } |
92 | 90 |
|
| 91 | + # TODO: This is only called once on Form declaration. |
| 92 | + # Making the challenge always the same. |
93 | 93 | def __init__(self, *args, **kwargs): |
94 | | - widget_options = {key: kwargs.pop(key, None) for key in AltchaWidget.default_options} |
| 94 | + import json |
| 95 | + |
| 96 | + challengeurl = kwargs.pop("challengeurl", None) |
| 97 | + challengejson = kwargs.pop("challengejson", None) |
| 98 | + |
| 99 | + # If no ``challengeurl`` is provided, auto-generate ``challengejson`` |
| 100 | + if challengeurl is None and challengejson is None: |
| 101 | + challenge = get_altcha_challenge() |
| 102 | + challengejson = json.dumps(challenge.__dict__) |
| 103 | + |
| 104 | + # Prepare widget options |
| 105 | + widget_options = { |
| 106 | + "challengeurl": challengeurl, |
| 107 | + "challengejson": challengejson, |
| 108 | + } |
| 109 | + |
| 110 | + # Include any other ALTCHA options passed |
| 111 | + for key in AltchaWidget.default_options: |
| 112 | + if key not in widget_options: |
| 113 | + widget_options[key] = kwargs.pop(key, None) |
| 114 | + |
| 115 | + # Assign the updated widget |
95 | 116 | kwargs["widget"] = AltchaWidget(**widget_options) |
96 | 117 | super().__init__(*args, **kwargs) |
97 | 118 |
|
@@ -124,12 +145,3 @@ def get_altcha_challenge(): |
124 | 145 | ) |
125 | 146 | ) |
126 | 147 | return challenge |
127 | | - |
128 | | - |
129 | | -@require_GET |
130 | | -def get_altcha_challenge_view(request): |
131 | | - try: |
132 | | - challenge = get_altcha_challenge() |
133 | | - return JsonResponse(challenge.__dict__) |
134 | | - except Exception as e: |
135 | | - return JsonResponse({"error": f"Failed to create challenge: {str(e)}"}, status=500) |
|
0 commit comments