├── hcaptcha ├── __init__.py ├── migrations │ └── __init__.py ├── apps.py ├── templates │ └── hcaptcha │ │ └── forms │ │ └── widgets │ │ └── hcaptcha_widget.html ├── settings.py ├── widgets.py └── fields.py ├── .gitignore ├── setup.py ├── MANIFEST.in ├── setup.cfg ├── LICENSE └── README.rst /hcaptcha/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /hcaptcha/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.pyc 3 | *.egg-info 4 | build -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() 4 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | recursive-include hcaptcha/templates * 4 | recursive-include docs * 5 | -------------------------------------------------------------------------------- /hcaptcha/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class HcaptchaConfig(AppConfig): 5 | name = 'hcaptcha' 6 | -------------------------------------------------------------------------------- /hcaptcha/templates/hcaptcha/forms/widgets/hcaptcha_widget.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | -------------------------------------------------------------------------------- /hcaptcha/settings.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | JS_API_URL = getattr(settings, 'HCAPTCHA_JS_API_URL', 'https://hcaptcha.com/1/api.js') 4 | VERIFY_URL = getattr(settings, 'HCAPTCHA_VERIFY_URL', 'https://hcaptcha.com/siteverify') 5 | SITEKEY = getattr(settings, 'HCAPTCHA_SITEKEY', '10000000-ffff-ffff-ffff-000000000001') 6 | SECRET = getattr(settings, 'HCAPTCHA_SECRET', '0x0000000000000000000000000000000000000000') 7 | TIMEOUT = getattr(settings, 'HCAPTCHA_TIMEOUT', 5) 8 | DEFAULT_CONFIG = getattr(settings, 'HCAPTCHA_DEFAULT_CONFIG', {}) 9 | PROXIES = getattr(settings, 'HCAPTCHA_PROXIES', {}) 10 | -------------------------------------------------------------------------------- /hcaptcha/widgets.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from django import forms 4 | 5 | from hcaptcha.settings import JS_API_URL, SITEKEY 6 | 7 | 8 | class hCaptchaWidget(forms.Widget): 9 | template_name = 'hcaptcha/forms/widgets/hcaptcha_widget.html' 10 | 11 | def __init__(self, *args, **kwargs): 12 | self.extra_url = {} 13 | super().__init__(*args, **kwargs) 14 | 15 | def value_from_datadict(self, data, files, name): 16 | return data.get('h-captcha-response') 17 | 18 | def build_attrs(self, base_attrs, extra_attrs=None): 19 | attrs = super().build_attrs(base_attrs, extra_attrs) 20 | attrs['data-sitekey'] = SITEKEY 21 | return attrs 22 | 23 | def get_context(self, name, value, attrs): 24 | context = super().get_context(name, value, attrs) 25 | context['api_url'] = JS_API_URL 26 | if self.extra_url: 27 | context['api_url'] += '?' + urlencode(self.extra_url) 28 | return context 29 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = django-hCaptcha 3 | version = 0.2.0 4 | description = Django hCaptcha provides a simple way to protect your django forms using hCaptcha 5 | long_description = file: README.rst 6 | url = https://github.com/AndrejZbin 7 | author = Andrej Zbín 8 | author_email = zbin.andrej@gmail.com 9 | license = BSD-3-Clause 10 | classifiers = 11 | Environment :: Web Environment 12 | Framework :: Django 13 | Framework :: Django :: 2.2 14 | Framework :: Django :: 3.2 15 | Framework :: Django :: 4.0 16 | Intended Audience :: Developers 17 | License :: OSI Approved :: BSD License 18 | Operating System :: OS Independent 19 | Programming Language :: Python 20 | Programming Language :: Python :: 3 21 | Programming Language :: Python :: 3 :: Only 22 | Programming Language :: Python :: 3.6 23 | Programming Language :: Python :: 3.7 24 | Programming Language :: Python :: 3.8 25 | Programming Language :: Python :: 3.9 26 | Topic :: Internet :: WWW/HTTP 27 | Topic :: Internet :: WWW/HTTP :: Dynamic Content 28 | 29 | [options] 30 | include_package_data = true 31 | packages = find: -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Andrej Zbín 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /hcaptcha/fields.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import json 3 | from urllib.error import HTTPError 4 | from urllib.parse import urlencode 5 | from urllib.request import build_opener, Request, ProxyHandler 6 | 7 | from django import forms 8 | from django.utils.translation import gettext_lazy as _ 9 | 10 | from hcaptcha.settings import DEFAULT_CONFIG, PROXIES, SECRET, TIMEOUT, VERIFY_URL 11 | from hcaptcha.widgets import hCaptchaWidget 12 | 13 | 14 | class hCaptchaField(forms.Field): 15 | widget = hCaptchaWidget 16 | default_error_messages = { 17 | 'error_hcaptcha': _('hCaptcha could not be verified.'), 18 | 'invalid_hcaptcha': _('hCaptcha could not be verified.'), 19 | 'required': _('Please prove you are a human.'), 20 | } 21 | 22 | def __init__(self, **kwargs): 23 | superclass_parameters = inspect.signature(super().__init__).parameters 24 | superclass_kwargs = {} 25 | widget_settings = DEFAULT_CONFIG.copy() 26 | for key, value in kwargs.items(): 27 | if key in superclass_parameters: 28 | superclass_kwargs[key] = value 29 | else: 30 | widget_settings[key] = value 31 | 32 | widget_url_settings = {} 33 | for prop in filter(lambda p: p in widget_settings, ('onload', 'render', 'hl')): 34 | widget_url_settings[prop] = widget_settings[prop] 35 | del widget_settings[prop] 36 | self.widget_settings = widget_settings 37 | 38 | super().__init__(**superclass_kwargs) 39 | 40 | self.widget.extra_url = widget_url_settings 41 | 42 | def widget_attrs(self, widget): 43 | attrs = super().widget_attrs(widget) 44 | for key, value in self.widget_settings.items(): 45 | attrs['data-%s' % key] = value 46 | return attrs 47 | 48 | def validate(self, value): 49 | super().validate(value) 50 | opener = build_opener(ProxyHandler(PROXIES)) 51 | post_data = urlencode({ 52 | 'secret': SECRET, 53 | 'response': value, 54 | }).encode() 55 | request = Request(VERIFY_URL, post_data) 56 | try: 57 | response = opener.open(request, timeout=TIMEOUT) 58 | except HTTPError: 59 | raise forms.ValidationError(self.error_messages['error_hcaptcha'], code='error_hcaptcha') 60 | 61 | response_data = json.loads(response.read().decode("utf-8")) 62 | 63 | if not response_data.get('success'): 64 | raise forms.ValidationError(self.error_messages['invalid_hcaptcha'], code='invalid_hcaptcha') 65 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============== 2 | Django hCaptcha 3 | =============== 4 | 5 | Django hCaptcha provides a simple way to protect your django forms using `hCaptcha `_. 6 | 7 | Configuration 8 | ------------- 9 | 10 | Add "hcaptcha" to your INSTALLED_APPS setting like this:: 11 | 12 | INSTALLED_APPS = [ 13 | ... 14 | 'hcaptcha', 15 | ] 16 | 17 | For development purposes no further configuration is required. By default, django-hCaptcha will use dummy keys. 18 | 19 | For production, you'll need to obtain your hCaptcha site key and secret key and add them to you settings:: 20 | 21 | HCAPTCHA_SITEKEY = '' 22 | HCAPTCHA_SECRET = '' 23 | 24 | 25 | You can also configure your hCaptcha widget globally (`see all options `_):: 26 | 27 | HCAPTCHA_DEFAULT_CONFIG = { 28 | 'onload': 'name_of_js_function', 29 | 'render': 'explicit', 30 | 'theme': 'dark', # do not use data- prefix 31 | 'size': 'compact', # do not use data- prefix 32 | ... 33 | } 34 | 35 | If you need to, you can also override default hcaptcha endpoints:: 36 | 37 | 38 | HCAPTCHA_JS_API_URL = 'https://hcaptcha.com/1/api.js' 39 | HCAPTCHA_VERIFY_URL = 'https://hcaptcha.com/siteverify' 40 | 41 | Use proxies:: 42 | 43 | HCAPTCHA_PROXIES = { 44 | 'http': 'http://127.0.0.1:8000', 45 | } 46 | 47 | Change default verification timeout:: 48 | 49 | HCAPTCHA_TIMEOUT = 5 50 | 51 | 52 | 53 | Usage 54 | ----------- 55 | 56 | Simply add hCaptchaField to your forms:: 57 | 58 | from hcaptcha.fields import hCaptchaField 59 | 60 | class Forms(forms.Form): 61 | .... 62 | hcaptcha = hCaptchaField() 63 | .... 64 | 65 | In your template, if you need to, you can then use `{{ form.hcaptcha }}` to access the field. 66 | 67 | You can override default config by passing additional arguments:: 68 | 69 | class Forms(forms.Form): 70 | .... 71 | hcaptcha = hCaptchaField(theme='dark', size='compact') 72 | .... 73 | 74 | 75 | How it Works 76 | ------------------ 77 | 78 | When a form is submitted by a user, hCaptcha's JavaScript will send two POST parameters to your backend, `g-captcha-resposne` and `h-captcha-response`. These will be received by your app and will be used to complete the `hcaptcha` form field in your backend code. 79 | 80 | When your app receives these two values, the following will happen: 81 | 82 | - Your backend will send these values to the hCaptcha servers 83 | - Their servers will indicate whether the values in the fields are correct 84 | - If so, your `hcaptcha` form field will validate correctly 85 | 86 | Unit Tests 87 | -------------- 88 | You will need to disable the hCaptcha field in your unit tests, since your tests obviously cannot complete the hCaptcha successfully. One way to do so might be something like: 89 | 90 | .. code-block:: python 91 | 92 | from unittest.mock import MagicMock, patch 93 | 94 | from django.test import TestCase 95 | 96 | @patch("hcaptcha.fields.hCaptchaField.validate", return_value=True) 97 | class ContactTest(TestCase): 98 | test_msg = { 99 | "name": "pandora", 100 | "message": "xyz", 101 | "hcaptcha": "xxx", # Any truthy value is fine 102 | } 103 | 104 | def test_something(self, mock: MagicMock) -> None: 105 | response = self.client.post("/contact/", self.test_msg) 106 | self.assertEqual(response.status_code, HTTP_302_FOUND) 107 | --------------------------------------------------------------------------------