Example #1
0
def math_clean(form):
    """
    Cleans a form, validating answer to math question in the process.
    The given ``form`` must be an instance of either ``MathCaptchaModelForm`` or ``MathCaptchaForm``.
    Answer keys are communicated in the ``math_captcha_question`` field which is evaluated to give the correct answer
    after being validated against the ``SECRET_KEY``
    """
    try:
        value = form.cleaned_data['math_captcha_field']
        test_secret, question = decode(form.cleaned_data['math_captcha_question'])
        assert len(test_secret) == 40 and question
    except (TypeError, AssertionError):
        # problem decoding, junky data
        raise forms.ValidationError('Invalid token')
    except KeyError:
        return
    
    if encode(question) != form.cleaned_data['math_captcha_question']:
        # security problem, hack attempt
        raise forms.ValidationError('Invalid token')
    if eval(question) != value:
        raise forms.ValidationError('Wrong answer, try again')
Example #2
0
 def render(self, name, value, attrs):
     aquestion = question()
     value = super(MathWidget, self).render(name, value, attrs)
     hidden = '<input type="hidden" value="%s" name="math_captcha_question"/>' %  encode(aquestion)
     return value.replace('<input', '%s %s = <input' % (hidden, aquestion))