Skip to content

Commit

Permalink
Merge branch 'recaptcha'
Browse files Browse the repository at this point in the history
  • Loading branch information
geelweb committed Mar 19, 2024
2 parents 3c3f203 + a69578c commit 5d223d8
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 12 deletions.
1 change: 1 addition & 0 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ jobs:
#if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
pip install Django==3.2
pip install django-widget-tweaks==1.4.8
pip install requests
- name: Test
run: |
python runtests.py
Expand Down
2 changes: 1 addition & 1 deletion contactform/templatetags/contact_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def contact_form_btn(label, form_id):
btn_attrs['type'] = 'submit'

btn = """<button %s>%s</button>""" % (
' '.join(['%s="%s"' % (k, btn_attrs[k]) for k in btn_attrs if btn_attrs[k] != '']),
' '.join(['%s="%s"' % (k, btn_attrs[k].strip()) for k in btn_attrs if btn_attrs[k] != '']),
label)

if recaptcha_enabled:
Expand Down
49 changes: 49 additions & 0 deletions contactform/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.test import RequestFactory, TestCase, override_settings
from django.urls import reverse
from .forms import ContactForm
from unittest.mock import MagicMock, patch

class ContactTestCase(TestCase):
def test_form_displayed(self):
Expand Down Expand Up @@ -105,6 +106,54 @@ def test_form_title_not_displayed(self):
self.assertContains(resp, 'csrfmiddlewaretoken', status_code=200)
self.assertNotContains(resp, '<h3>Contact us</h3>', status_code=200)

@override_settings(CONTACTFORM_RECIPIENTS=['[email protected]'])
@override_settings(GOOGLE_RECAPTCHA_ENABLED=True)
@override_settings(GOOGLE_RECAPTCHA_SECRET='recaptcha-secret')
@patch('contactform.views.requests')
def test_post_with_invalid_recaptcha(self, mock_requests):
""" Tests than the email is not sent where recaptcha fail the
validation
"""

mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {'success': False}
mock_requests.post.return_value = mock_response

resp = self.client.post(reverse('contactform:index'), {
'email': '[email protected]',
'phone': '06 00 00 00 00',
'comment': 'This is my message content',
'g-recaptcha-response': 'abcdefgh'})

self.assertEqual(len(mail.outbox), 0)

self.assertContains(resp, 'Thanks for your message', status_code=200)

@override_settings(CONTACTFORM_RECIPIENTS=['[email protected]'])
@override_settings(GOOGLE_RECAPTCHA_ENABLED=True)
@override_settings(GOOGLE_RECAPTCHA_SECRET='recaptcha-secret')
@patch('contactform.views.requests')
def test_post_with_valid_recaptcha(self, mock_requests):
""" Tests than the email is not sent where recaptcha fail the
validation
"""

mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {'success': True}
mock_requests.post.return_value = mock_response

resp = self.client.post(reverse('contactform:index'), {
'email': '[email protected]',
'phone': '06 00 00 00 00',
'comment': 'This is my message content',
'g-recaptcha-response': 'abcdefgh'})

self.assertEqual(len(mail.outbox), 1)

self.assertContains(resp, 'Thanks for your message', status_code=200)


class ContactFormTagTest(TestCase):
def setUp(self):
Expand Down
36 changes: 25 additions & 11 deletions contactform/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,23 @@
from .forms import ContactForm
from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
import requests

def index(request):
form = ContactForm(request.POST or None)
if form.is_valid():
recaptcha_enabled = getattr(settings, 'GOOGLE_RECAPTCHA_ENABLED', False)
recaptcha_valid = True
if recaptcha_enabled:
secret_key = settings.GOOGLE_RECAPTCHA_SECRET
data = {
'response': request.POST.get('g-recaptcha-response'),
'secret': secret_key
}
resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result_json = resp.json()
recaptcha_valid = result_json.get('success')

email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
comment = form.cleaned_data['comment']
Expand All @@ -25,17 +38,18 @@ def index(request):
'phone': phone,
'comment': comment})

recipients = settings.CONTACTFORM_RECIPIENTS
try:
email = EmailMessage(
getattr(settings, 'CONTACTFORM_SUBJECT', _('New message')),
message,
getattr(settings, 'CONTACTFORM_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL),
recipients,
reply_to=[email])
email.send(fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')
if recaptcha_valid:
recipients = settings.CONTACTFORM_RECIPIENTS
try:
email = EmailMessage(
getattr(settings, 'CONTACTFORM_SUBJECT', _('New message')),
message,
getattr(settings, 'CONTACTFORM_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL),
recipients,
reply_to=[email])
email.send(fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')


messages.success(request, _('Your message has been sent.'), extra_tags='contactform')
Expand Down

0 comments on commit 5d223d8

Please sign in to comment.