captcha.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import requests
  2. from django.core.exceptions import ValidationError
  3. from django.utils.translation import gettext as _
  4. def recaptcha_test(request):
  5. r = requests.post(
  6. "https://www.google.com/recaptcha/api/siteverify",
  7. data={
  8. "secret": request.settings.recaptcha_secret_key,
  9. "response": request.data.get("captcha"),
  10. "remoteip": request.user_ip,
  11. },
  12. )
  13. if r.status_code == 200:
  14. response_json = r.json()
  15. if not response_json.get("success"):
  16. raise ValidationError(_("Please try again."))
  17. else:
  18. raise ValidationError(_("Failed to contact reCAPTCHA API."))
  19. def qacaptcha_test(request):
  20. answer = request.data.get("captcha", "").lower().strip()
  21. valid_answers = get_valid_qacaptcha_answers(request.settings)
  22. if answer not in valid_answers:
  23. raise ValidationError(_("Entered answer is incorrect."))
  24. def get_valid_qacaptcha_answers(settings):
  25. valid_answers = [i.strip() for i in settings.qa_answers.lower().splitlines()]
  26. return filter(len, valid_answers)
  27. def nocaptcha_test(request):
  28. return # no captcha means no validation
  29. CAPTCHA_TESTS = {"re": recaptcha_test, "qa": qacaptcha_test, "no": nocaptcha_test}
  30. def test_request(request):
  31. CAPTCHA_TESTS[request.settings.captcha_type](request)