diff --git a/benefits/core/context_processors.py b/benefits/core/context_processors.py index d9120a861..9c39beaf3 100644 --- a/benefits/core/context_processors.py +++ b/benefits/core/context_processors.py @@ -36,14 +36,3 @@ def authentication(request): def debug(request): """Context processor adds debug information to request context.""" return {"debug": session.context_dict(request)} - - -def recaptcha(request): - """Context processor adds recaptcha information to request context.""" - return { - "recaptcha": { - "api_url": settings.RECAPTCHA_API_URL, - "enabled": settings.RECAPTCHA_ENABLED, - "site_key": settings.RECAPTCHA_SITE_KEY, - } - } diff --git a/benefits/core/middleware.py b/benefits/core/middleware.py index 2e24728f2..42e2d0331 100644 --- a/benefits/core/middleware.py +++ b/benefits/core/middleware.py @@ -13,7 +13,7 @@ from django.utils.deprecation import MiddlewareMixin from django.views import i18n -from . import analytics, session, viewmodels +from . import analytics, recaptcha, session, viewmodels logger = logging.getLogger(__name__) @@ -174,3 +174,16 @@ def process_exception(self, request, exception): self.azure_logger.exception(msg, exc_info=exception) return None + + +class RecaptchaEnabled(MiddlewareMixin): + """Middleware configures the request with required reCAPTCHA settings.""" + + def process_request(self, request): + if settings.RECAPTCHA_ENABLED: + request.recaptcha = { + "data_field": recaptcha.DATA_FIELD, + "script_api": settings.RECAPTCHA_API_KEY_URL, + "site_key": settings.RECAPTCHA_SITE_KEY, + } + return None diff --git a/benefits/core/recaptcha.py b/benefits/core/recaptcha.py index dd3a9a036..e6f19592c 100644 --- a/benefits/core/recaptcha.py +++ b/benefits/core/recaptcha.py @@ -6,7 +6,7 @@ from django.conf import settings -_POST_DATA = "g-recaptcha-response" +DATA_FIELD = "g-recaptcha-response" def has_error(form) -> bool: @@ -22,10 +22,10 @@ def verify(form_data: dict) -> bool: if not settings.RECAPTCHA_ENABLED: return True - if not form_data or _POST_DATA not in form_data: + if not form_data or DATA_FIELD not in form_data: return False - payload = dict(secret=settings.RECAPTCHA_SECRET_KEY, response=form_data[_POST_DATA]) + payload = dict(secret=settings.RECAPTCHA_SECRET_KEY, response=form_data[DATA_FIELD]) response = requests.post(settings.RECAPTCHA_VERIFY_URL, payload).json() return bool(response["success"]) diff --git a/benefits/core/templates/core/base.html b/benefits/core/templates/core/base.html index ac0446706..a40889acb 100644 --- a/benefits/core/templates/core/base.html +++ b/benefits/core/templates/core/base.html @@ -129,20 +129,22 @@