Skip to main content

Pluggable captcha support for Django REST Framework.

Project description

DRF-CaptchaX

Tests PyPI version Python Versions Django Versions License: MIT

A powerful and flexible CAPTCHA integration for Django REST Framework with multiple storage backends and customization options.

Features

  • 🚀 Easy integration with Django REST Framework
  • 🎨 Highly customizable CAPTCHA generation
  • 💾 Multiple storage backends (Memory, Redis)
  • ✨ Simple validation process
  • 🔒 Secure by design
  • 📱 Mobile-friendly
  • 🌐 Internationalization support
  • ⚡ High performance
  • 🧪 Comprehensive test suite

Installation

pip install drf-captchax

Quick Start

  1. Add 'captchax' to your INSTALLED_APPS:
INSTALLED_APPS = [
    ...
    'rest_framework',
    'captchax',
]
  1. Include CAPTCHA URLs in your project's urls.py:
from django.urls import path, include

urlpatterns = [
    ...
    path('captcha/', include('captchax.urls')),
]
  1. Configure CAPTCHA settings in your Django settings:
CAPTCHAX = {
    # CAPTCHA Generation
    'LENGTH': 6,                    # Length of CAPTCHA text
    'WIDTH': 200,                   # Image width
    'HEIGHT': 60,                   # Image height
    'FONT_SIZE': 36,               # Font size
    'BACKGROUND_COLOR': '#ffffff',  # Background color
    'TEXT_COLOR': '#000000',       # Text color
    'NOISE_LEVEL': 20,             # Noise level (0-100)
    'USE_LINES': True,             # Add random lines
    'USE_DOTS': True,              # Add random dots
    
    # Validation
    'TIMEOUT': 300,                # CAPTCHA validity period in seconds
    'CASE_SENSITIVE': False,       # Case-sensitive validation
    'MAX_ATTEMPTS': 5,             # Maximum validation attempts
    
    # Storage Backend
    'BACKEND': 'captchax.backend.memory.MemoryBackend',  # Default backend
    # For Redis backend:
    # 'BACKEND': 'captchax.backend.redis.RedisBackend',
    # 'REDIS_URL': 'redis://localhost:6379/0',
    # 'REDIS_PREFIX': 'captchax:',
}
  1. Use in your serializers:
from rest_framework import serializers
from captchax.validator import CaptchaValidator

class RegistrationSerializer(serializers.Serializer):
    username = serializers.CharField()
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)
    captcha_id = serializers.CharField()
    captcha_text = serializers.CharField(validators=[CaptchaValidator()])
  1. Frontend Integration:
<!-- Template -->
<form method="post" action="/api/register/">
    <!-- Your form fields -->
    <div class="captcha-container">
        <img id="captcha-image" alt="CAPTCHA">
        <button type="button" onclick="refreshCaptcha()"></button>
        <input type="hidden" name="captcha_id" id="captcha-id">
        <input type="text" name="captcha_text" required>
    </div>
</form>

<!-- JavaScript -->
<script>
function refreshCaptcha() {
    fetch('/captcha/generate/')
        .then(response => response.json())
        .then(data => {
            document.getElementById('captcha-image').src = data.image;
            document.getElementById('captcha-id').value = data.captcha_id;
        });
}

// Refresh CAPTCHA on page load
document.addEventListener('DOMContentLoaded', refreshCaptcha);
</script>

<!-- Optional CSS -->
<style>
.captcha-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 15px 0;
}
</style>

Advanced Usage

Custom Validation

from captchax.validator import CaptchaValidator

# Case-sensitive validation
validator = CaptchaValidator(case_sensitive=True)

# Custom maximum attempts
validator = CaptchaValidator(max_attempts=3)

# Custom backend
from captchax.backend.redis import RedisBackend
validator = CaptchaValidator(
    backend_class=RedisBackend,
    redis_url='redis://localhost:6379/0'
)

Custom CAPTCHA Generation

from captchax.captcha import CaptchaGenerator

generator = CaptchaGenerator(
    length=8,
    width=300,
    height=80,
    font_size=42,
    background_color='#f0f0f0',
    text_color='#333333',
    noise_level=30
)

captcha_id, image = generator.generate_image()

Redis Backend Configuration

For production environments, it's recommended to use the Redis backend:

CAPTCHAX = {
    'BACKEND': 'captchax.backend.redis.RedisBackend',
    'REDIS_URL': 'redis://localhost:6379/0',
    'REDIS_PREFIX': 'captchax:',
    # Other settings...
}

API Endpoints

  • GET /captcha/generate/: Generate a new CAPTCHA

    • Returns: {"captcha_id": "...", "image": "data:image/png;base64,..."}
  • POST /captcha/validate/: Validate a CAPTCHA response

    • Data: {"captcha_id": "...", "captcha_text": "..."}
    • Returns: 200 OK if valid, 400 Bad Request if invalid

Testing

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=captchax

Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes and commit: git commit -m 'Add feature'
  4. Push to the branch: git push origin feature-name
  5. Submit a pull request

Please make sure to:

  • Follow the existing code style
  • Add tests for new features
  • Update documentation as needed

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

Created and maintained by Alireza Alibolandi.

Support

  • 📫 Report issues on GitHub

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf_captchax-0.1.2.tar.gz (400.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

drf_captchax-0.1.2-py3-none-any.whl (396.6 kB view details)

Uploaded Python 3

File details

Details for the file drf_captchax-0.1.2.tar.gz.

File metadata

  • Download URL: drf_captchax-0.1.2.tar.gz
  • Upload date:
  • Size: 400.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for drf_captchax-0.1.2.tar.gz
Algorithm Hash digest
SHA256 4792b13f57aa0337e6b7ed5c777a6c9091f2743f7138e2e7e8edb8304b281da0
MD5 87fdacddb1a6a4b5b4cb41a44ca6f8f1
BLAKE2b-256 7b761c0e5cbbb209f07a1cb240af1b27bbc4ce698694453adb3c16e7c3211de8

See more details on using hashes here.

File details

Details for the file drf_captchax-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: drf_captchax-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 396.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for drf_captchax-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f7ce90fbd3402ce21823b4991b95a355ee0a17edbdee3d1e67cd700aba5b3b6e
MD5 8fe4feb44c03874fe4b8210c5cd233cf
BLAKE2b-256 b4e353e558bef8ba03f3bd5f65888cc50987780e634c166e86eb1be5ae173b24

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page