Skip to content

Commit bf9626d

Browse files
committed
Move the generate challenge at the widget level #235
Signed-off-by: tdruez <[email protected]>
1 parent a5ff954 commit bf9626d

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

django_altcha/__init__.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,15 @@ def __init__(self, **kwargs):
117117
def get_context(self, name, value, attrs):
118118
context = super().get_context(name, value, attrs)
119119
context["js_src_url"] = self.js_src_url
120-
context["widget"]["altcha_options"] = self.options # Pass options to template
120+
121+
# Generate challengejson if no challengeurl is provided.
122+
# A new challenge is generated each time the widget is rendered.
123+
challengeurl = self.options.get("challengeurl")
124+
if not challengeurl:
125+
challenge = get_altcha_challenge()
126+
self.options["challengejson"] = json.dumps(challenge.__dict__)
127+
128+
context["widget"]["altcha_options"] = self.options
121129
return context
122130

123131

@@ -130,30 +138,15 @@ class AltchaField(forms.Field):
130138
}
131139

132140
# TODO: This is only called once on Form declaration.
133-
# Making the challenge always the same.
134141
def __init__(self, *args, **kwargs):
135-
challengeurl = kwargs.pop("challengeurl", None)
136-
challengejson = kwargs.pop("challengejson", None)
137-
138-
# If no ``challengeurl`` is provided, auto-generate ``challengejson``
139-
if challengeurl is None and challengejson is None:
140-
challenge = get_altcha_challenge()
141-
challengejson = json.dumps(challenge.__dict__)
142-
143-
# Prepare widget options
144-
widget_options = {
145-
"challengeurl": challengeurl,
146-
"challengejson": challengejson,
147-
}
148-
142+
widget_options = {}
149143
# Include any other ALTCHA options passed
150144
for key in AltchaWidget.default_options:
151145
if key not in widget_options:
152146
widget_options[key] = kwargs.pop(key, None)
153147

154148
# Assign the updated widget
155149
kwargs["widget"] = AltchaWidget(**widget_options)
156-
kwargs["widget"].attrs.update()
157150
super().__init__(*args, **kwargs)
158151

159152
def validate(self, value):

0 commit comments

Comments
 (0)