Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Django REST Framework #236

Merged
merged 2 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions captcha/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from rest_framework import serializers
from rest_framework.fields import empty

from captcha.validators import captcha_validate


class CaptchaSerializer(serializers.Serializer):
"""Serializer captcha code and captcha hashkey"""

captcha_code = serializers.CharField(max_length=32, write_only=True, required=True)
captcha_hashkey = serializers.CharField(
max_length=40, write_only=True, required=True
)

def run_validation(self, data=empty):
values = super().run_validation(data=data)
captcha_validate(values["captcha_hashkey"], values["captcha_code"])
return values


class CaptchaModelSerializer(serializers.ModelSerializer):
"""Model serializer captcha code and captcha hashkey"""

captcha_code = serializers.CharField(max_length=32, write_only=True, required=True)
captcha_hashkey = serializers.CharField(
max_length=40, write_only=True, required=True
)

def run_validation(self, data=empty):
values = super().run_validation(data=data)
captcha_validate(values["captcha_hashkey"], values["captcha_code"])
return values
47 changes: 47 additions & 0 deletions captcha/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,53 @@ def test_empty_pool_fallback(self):
self.assertEqual(CaptchaStore.objects.count(), 1)
settings.CAPTCHA_GET_FROM_POOL = __current_test_get_from_pool_setting

def test_serializer(self):
r = self.client.post(
reverse("captcha-test-serializer"),
dict(
captcha_code=self.default_store.response,
captcha_hashkey=self.default_store.hashkey,
),
)
self.assertEqual(r.status_code, 200)

def test_wrong_serializer(self):
r = self.client.post(
reverse("captcha-test-serializer"),
dict(
captcha_code="xxx",
captcha_hashkey="wrong hash",
),
)
self.assertEqual(r.status_code, 400)
self.assertEqual(json.loads(r.content), {"error": "Invalid CAPTCHA"})


def test_model_serializer(self):
r = self.client.post(
reverse("captcha-test-model-serializer"),
dict(
captcha_code=self.default_store.response,
captcha_hashkey=self.default_store.hashkey,
subject="xxx",
sender="[email protected]",
),
)
self.assertEqual(r.status_code, 200)

def test_wrong_model_serializer(self):
r = self.client.post(
reverse("captcha-test-model-serializer"),
dict(
captcha_code="xxx",
captcha_hashkey="wrong hash",
subject="xxx",
sender="[email protected]",
),
)
self.assertEqual(r.status_code, 400)
self.assertEqual(json.loads(r.content), {"error": "Invalid CAPTCHA"})


def trivial_challenge():
return "trivial", "trivial"
Expand Down
4 changes: 4 additions & 0 deletions captcha/tests/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,16 @@
test_model_form,
test_non_required,
test_per_form_format,
test_serializer,
test_model_serializer,
)


urlpatterns = [
re_path(r"test/$", test, name="captcha-test"),
re_path(r"test-modelform/$", test_model_form, name="captcha-test-model-form"),
re_path(r"test-serializer/$", test_serializer, name="captcha-test-serializer"),
re_path(r"test-model-serializer/$", test_model_serializer, name="captcha-test-model-serializer"),
re_path(
r"test2/$", test_custom_error_message, name="captcha-test-custom-error-message"
),
Expand Down
28 changes: 27 additions & 1 deletion captcha/tests/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.template import engines
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from rest_framework import serializers
from captcha.fields import CaptchaField

from captcha.serializers import CaptchaSerializer, CaptchaModelSerializer

TEST_TEMPLATE = r"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Expand Down Expand Up @@ -126,3 +130,25 @@ class CaptchaTestForm(forms.Form):
captcha2 = CaptchaField(id_prefix="form2")

return _test(request, CaptchaTestForm)


@api_view(['POST'])
def test_serializer(request):
serializer = CaptchaSerializer(data=request.POST)
serializer.is_valid(raise_exception=True)
return Response(status=status.HTTP_200_OK)


@api_view(['POST'])
def test_model_serializer(request):
class UserCaptchaModelSerializer(CaptchaModelSerializer):
subject = serializers.CharField(max_length=100)
sender = serializers.EmailField()

class Meta:
model = User
fields = ("subject", "sender", "captcha_code", "captcha_hashkey")

serializer = UserCaptchaModelSerializer(data=request.POST)
serializer.is_valid(raise_exception=True)
return Response(status=status.HTTP_200_OK)
32 changes: 32 additions & 0 deletions captcha/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from rest_framework import exceptions

import django
from django.utils import timezone


if django.VERSION >= (3, 0):
from django.utils.translation import gettext_lazy as gettext_lazy
else:
from django.utils.translation import ugettext_lazy as gettext_lazy

from captcha.conf import settings
from captcha.models import CaptchaStore


def captcha_validate(hashkey, response):
hashkey, response = hashkey.lower(), response.lower()

if not settings.CAPTCHA_GET_FROM_POOL:
CaptchaStore.remove_expired()
if settings.CAPTCHA_TEST_MODE and response.lower() == "passed":
try:
CaptchaStore.objects.get(hashkey=hashkey).delete()
except CaptchaStore.DoesNotExist:
pass
else:
try:
CaptchaStore.objects.get(
response=response, hashkey=hashkey, expiration__gt=timezone.now()
).delete()
except CaptchaStore.DoesNotExist:
raise exceptions.ValidationError({"error": gettext_lazy("Invalid CAPTCHA")})
28 changes: 28 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,31 @@ Example usage ajax refresh
$('#id_captcha_0').val(result['key'])
});
});

Example usage in Django REST Framework
---------------------------------

To use CAPTCHA in a serializer, simply inherit ``CaptchaSerializer``::

from captcha.serializers import CaptchaSerializer
from rest_framework import serializers

class CheckCaptchaSerializer(CaptchaSerializer):
email = serializers.EmailField()

…or use ``CaptchaModelSerializer``::

from captcha.serializers import CaptchaModelSerializer
from rest_framework import serializers

class CheckCaptchaModelSerializer(CaptchaModelSerializer):
sender = serializers.EmailField()

class Meta:
model = User
fields = ("captcha_code", "captcha_hashkey", "sender")

``CaptchaSerializer`` and ``CaptchaModelSerializer`` implement the ``captcha_code`` and ``captcha_hashkey`` fields.
In case of invalid captcha or hash code an exception is raised::

raise exceptions.ValidationError({"error": gettext_lazy("Invalid CAPTCHA")})
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def run_tests(self):
"Django >= 4.2",
"Pillow >=6.2.0",
"django-ranged-response == 0.2.0",
"djangorestframework >= 3.15.0",
]
EXTRAS_REQUIRE = {"test": ("testfixtures",)}

Expand Down
1 change: 1 addition & 0 deletions testproject/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"django.contrib.sites",
"django.forms",
"django.contrib.messages",
"rest_framework",
"captcha",
]
FORM_RENDERER = "django.forms.renderers.TemplatesSetting"
Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ deps =
py{39,310,311,312}-django{42,50}: python3-memcached
jinja2
Pillow
djangorestframework

extras =
test
Expand Down
Loading