Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Feature: put a recaptcha check on account forms

NyanKiyoshi612c69061289
diff --git a/docs/guides.rst b/docs/guides.rst
index 8ae5dcc73d..9a228bbd92 100644
--- a/docs/guides.rst
+++ b/docs/guides.rst
@@ -6,3 +6,4 @@ Guides
guides/orders
guides/navigation
+ guides/recaptcha
diff --git a/docs/guides/recaptcha.rst b/docs/guides/recaptcha.rst
new file mode 100644
index 0000000000..f23f395fe7
--- /dev/null
+++ b/docs/guides/recaptcha.rst
@@ -0,0 +1,24 @@
+ReCaptcha
+=========
+
+
+Pre-requirements
+----------------
+
+You can get your API key set from `Google ReCaptcha
+<https://www.google.com/recaptcha/admin>`_.
+
+
+Enable and Set-up
+-----------------
+
+To enable ReCaptcha, you need to set those keys in your environment:
+
+1. ``ENABLE_RECAPTCHA`` to ``True``;
+2. ``RECAPTCHA_PUBLIC_KEY`` to your public/ site API key;
+3. ``RECAPTCHA_PRIVATE_KEY`` to your secret/ private API key.
+
+
+.. note::
+ You are not required to set your public and private keys for development use.
+ You only have to set them up if you are using Saleor for production (Google will remind you if you do not).
diff --git a/requirements.in b/requirements.in
index b2f3c353af..cb7bf94605 100644
--- a/requirements.in
+++ b/requirements.in
@@ -25,6 +25,7 @@ django-versatileimagefield>=1.0.1
django-webpack-loader>=0.3.0
django-celery-results
django-elasticsearch-dsl
+django-recaptcha
elasticsearch>=5.4,<6.0.0
elasticsearch-dsl>=5.0.0,<6.0.0
faker>=0.7.7
diff --git a/requirements.txt b/requirements.txt
index 59517656cd..bd8c1782de 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -42,6 +42,7 @@ django-payments==0.12.1
django-phonenumber-field==2.0.0
django-prices-openexchangerates==1.0.0
django-prices==1.0.0
+django-recaptcha==1.4.0
django-redis==4.8.0
django-render-block==0.5 # via django-templated-email
django-storages==1.6.5
diff --git a/saleor/account/forms.py b/saleor/account/forms.py
index 63cd65f72d..0b7a3119e0 100644
--- a/saleor/account/forms.py
+++ b/saleor/account/forms.py
@@ -1,3 +1,4 @@
+from captcha.fields import ReCaptchaField
from django import forms
from django.conf import settings
from django.contrib.auth import forms as django_forms, update_session_auth_hash
@@ -9,6 +10,14 @@ from ..account.models import User
from .i18n import AddressMetaForm, get_address_form_class
+class FormWithReCaptcha(forms.BaseForm):
+ def __new__(cls, *args, **kwargs):
+ if settings.ENABLE_RECAPTCHA:
+ cls.base_fields['_captcha'] = ReCaptchaField(
+ label=pgettext_lazy('Captcha field label', 'Are you human?'))
+ return super(FormWithReCaptcha, cls).__new__(cls)
+
+
def get_address_form(
data, country_code, initial=None, instance=None, **kwargs):
country_form = AddressMetaForm(data, initial=initial)
@@ -55,7 +64,7 @@ def logout_on_password_change(request, user):
update_session_auth_hash(request, user)
-class LoginForm(django_forms.AuthenticationForm):
+class LoginForm(django_forms.AuthenticationForm, FormWithReCaptcha):
username = forms.EmailField(
label=pgettext('Form field', 'Email'), max_length=75)
@@ -67,7 +76,7 @@ class LoginForm(django_forms.AuthenticationForm):
self.fields['username'].initial = email
-class SignupForm(forms.ModelForm):
+class SignupForm(forms.ModelForm, FormWithReCaptcha):
password = forms.CharField(
widget=forms.PasswordInput)
email = forms.EmailField(
@@ -100,7 +109,7 @@ class SignupForm(forms.ModelForm):
return user
-class PasswordResetForm(django_forms.PasswordResetForm):
+class PasswordResetForm(django_forms.PasswordResetForm, FormWithReCaptcha):
"""Allow resetting passwords.
This subclass overrides sending emails to use templated email.
diff --git a/saleor/settings.py b/saleor/settings.py
index f6c0250f96..e14e92d9f0 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -13,7 +13,14 @@ def get_list(text):
return [item.strip() for item in text.split(',')]
-DEBUG = ast.literal_eval(os.environ.get('DEBUG', 'True'))
+def get_bool(name, default_value):
+ if name in os.environ:
+ value = os.environ[name]
+ return ast.literal_eval(value)
+ return default_value
+
+
+DEBUG = get_bool('DEBUG', True)
SITE_ID = 1
@@ -90,8 +97,7 @@ EMAIL_BACKEND = email_config['EMAIL_BACKEND']
EMAIL_USE_TLS = email_config['EMAIL_USE_TLS']
EMAIL_USE_SSL = email_config['EMAIL_USE_SSL']
-ENABLE_SSL = ast.literal_eval(
- os.environ.get('ENABLE_SSL', 'False'))
+ENABLE_SSL = get_bool('ENABLE_SSL', False)
if ENABLE_SSL:
SECURE_SSL_REDIRECT = not DEBUG
@@ -215,14 +221,15 @@ INSTALLED_APPS = [
'django_filters',
'django_celery_results',
'impersonate',
- 'phonenumber_field']
+ 'phonenumber_field',
+ 'captcha']
if DEBUG:
MIDDLEWARE.append(
'debug_toolbar.middleware.DebugToolbarMiddleware')
INSTALLED_APPS.append('debug_toolbar')
-ENABLE_SILK = ast.literal_eval(os.environ.get('ENABLE_SILK', 'False'))
+ENABLE_SILK = get_bool('ENABLE_SILK', False)
if ENABLE_SILK:
MIDDLEWARE.insert(0, 'silk.middleware.SilkyMiddleware')
INSTALLED_APPS.append('silk')
@@ -332,8 +339,7 @@ AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
AWS_MEDIA_BUCKET_NAME = os.environ.get('AWS_MEDIA_BUCKET_NAME')
AWS_MEDIA_CUSTOM_DOMAIN = os.environ.get('AWS_MEDIA_CUSTOM_DOMAIN')
-AWS_QUERYSTRING_AUTH = ast.literal_eval(
- os.environ.get('AWS_QUERYSTRING_AUTH', 'False'))
+AWS_QUERYSTRING_AUTH = get_bool('AWS_QUERYSTRING_AUTH', False)
if AWS_STORAGE_BUCKET_NAME:
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
@@ -355,8 +361,7 @@ VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
VERSATILEIMAGEFIELD_SETTINGS = {
# Images should be pre-generated on Production environment
- 'create_images_on_demand': ast.literal_eval(
- os.environ.get('CREATE_IMAGES_ON_DEMAND', repr(DEBUG))),
+ 'create_images_on_demand': get_bool('CREATE_IMAGES_ON_DEMAND', DEBUG),
}
PLACEHOLDER_IMAGES = {
@@ -468,3 +473,15 @@ ALLOWED_STYLES = ['text-align']
DEFAULT_MENUS = {
'top_menu_name': 'navbar',
'bottom_menu_name': 'footer'}
+
+
+NOCAPTCHA = True
+
+ENABLE_RECAPTCHA = get_bool('ENABLE_RECAPTCHA', False)
+
+if 'RECAPTCHA_PUBLIC_KEY' in os.environ:
+ RECAPTCHA_PUBLIC_KEY = os.environ['RECAPTCHA_PUBLIC_KEY']
+
+if 'RECAPTCHA_PRIVATE_KEY' in os.environ:
+ RECAPTCHA_PRIVATE_KEY = os.environ['RECAPTCHA_PRIVATE_KEY']
+
diff --git a/tests/test_account.py b/tests/test_account.py
index 0ec1891ca9..7bb5afae6a 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -1,8 +1,11 @@
import json
+import os
+from unittest.mock import patch
from urllib.parse import urlencode
import i18naddress
import pytest
+from django.conf import settings
from django.core.exceptions import ValidationError
from django.http import QueryDict
from django.template import Context, Template
@@ -10,6 +13,7 @@ from django.urls import reverse
from django_countries.fields import Country
from saleor.account import forms, i18n
+from saleor.account.forms import LoginForm, PasswordResetForm, SignupForm
from saleor.account.templatetags.i18n_address_tags import format_address
from saleor.account.validators import validate_possible_number
@@ -218,3 +222,22 @@ def test_ajax_users_list(admin_client, admin_user, customer_user):
assert response.status_code == 200
assert resp_decoded == {'results': users_list}
+
+
[email protected](os.environ, {'RECAPTCHA_TESTING': 'True'})
+ 'form_cls, post_data', [
+ (LoginForm, {'username': '[email protected]', 'password': 'password'}),
+ (SignupForm, {'email': '[email protected]', 'password': 'password'}),
+ (PasswordResetForm, {'email': '[email protected]'}),
+ ])
+def test_requires_recaptcha(customer_user, form_cls, post_data):
+ params_passed_robot_check = post_data.copy()
+ params_passed_robot_check['g-recaptcha-response'] = 'PASSED'
+
+ with patch.object(settings, 'ENABLE_RECAPTCHA', False):
+ assert form_cls(data=post_data).is_valid()
+
+ with patch.object(settings, 'ENABLE_RECAPTCHA', True):
+ assert not form_cls(data=post_data).is_valid()
+ assert form_cls(data=params_passed_robot_check).is_valid()