Coverage for benefits / core / recaptcha.py: 53%
13 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 19:35 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 19:35 +0000
1"""
2The core application: helpers to work with reCAPTCHA.
3"""
5import requests
6from django.conf import settings
8DATA_FIELD = "g-recaptcha-response"
11def has_error(form) -> bool:
12 """True if the given form has a reCAPTCHA error. False otherwise."""
13 return any([s for (_, v) in form.errors.items() for s in v if "reCAPTCHA" in s])
16def verify(form_data: dict) -> bool:
17 """
18 Check with Google reCAPTCHA if the given response is a valid user.
19 See https://developers.google.com/recaptcha/docs/verify
20 """
21 if not settings.RECAPTCHA_ENABLED: 21 ↛ 24line 21 didn't jump to line 24 because the condition on line 21 was always true
22 return True
24 if not form_data or DATA_FIELD not in form_data:
25 return False
27 payload = dict(secret=settings.RECAPTCHA_SECRET_KEY, response=form_data[DATA_FIELD])
28 response = requests.post(settings.RECAPTCHA_VERIFY_URL, payload, timeout=settings.REQUESTS_TIMEOUT).json()
30 return bool(response["success"])