Skip to main content

Django REST Framework authentication library with Clerk integration

Project description

clerk-auth-django

Django REST Framework authentication library with Clerk integration.

Installation

pip install clerk-auth-django

Quick Start

1. Add to INSTALLED_APPS

# settings.py
INSTALLED_APPS = [
    # ...
    'clerk_auth',
]

2. Configure Clerk Settings

# settings.py
CLERK_AUTH = {
    'SECRET_KEY': 'sk_test_...',  # Required: Your Clerk secret key
    'USER_MODEL': 'auth.User',    # Your minimal user model
    'AUTO_CREATE_USER': True,     # Auto-create user on first auth (default: True)
}

3. Define Your User Model

# models.py
from clerk_auth.models import ClerkUser

class User(ClerkUser):
    """Minimal user model - only app-specific fields"""
    # clerk_id (PK) inherited from ClerkUser
    stripe_customer_id = models.CharField(max_length=255, null=True)
    subscription_tier = models.CharField(max_length=50, default='free')
    preferences = models.JSONField(default=dict)

4. Use in Your Views

# views.py
from rest_framework import viewsets
from clerk_auth.permissions import HasRole

class InvoiceViewSet(viewsets.ModelViewSet):
    permission_classes = [HasRole('admin')]

    def get_queryset(self):
        # Normal Django ForeignKey filtering!
        return self.request.user.invoices.all()

Features

Authentication

Automatic JWT verification and user creation:

# The authentication class automatically:
# 1. Validates JWT from Authorization header
# 2. Creates User record on first auth (if AUTO_CREATE_USER=True)
# 3. Attaches JWT claims to request.user.clerk_claims
# 4. Attaches org_role to request.user.org_role

Permissions

Role-based and permission-based access control:

from clerk_auth.permissions import HasRole, HasPermission, HasAnyRole

class AdminView(APIView):
    permission_classes = [HasRole('admin')]

class EditorView(APIView):
    permission_classes = [HasAnyRole('admin', 'editor')]

class InvoiceView(APIView):
    permission_classes = [HasPermission('read:invoices')]

Decorators

Function-based view support:

from clerk_auth.decorators import require_role, require_permission

@require_role('admin')
def admin_only_view(request):
    return Response({'message': 'Admin access granted'})

@require_permission('write:invoices')
def create_invoice(request):
    return Response({'message': 'Invoice created'})

Webhooks

Handle Clerk webhook events:

# urls.py
from clerk_auth.webhooks import ClerkWebhookView

urlpatterns = [
    path('webhooks/clerk/', ClerkWebhookView.as_view()),
]

# settings.py
CLERK_AUTH = {
    # ...
    'WEBHOOK_SECRET': 'whsec_...',
}

Configuration

Complete Configuration Reference

CLERK_AUTH = {
    # Required
    'SECRET_KEY': 'sk_test_...',

    # User Management
    'USER_MODEL': 'auth.User',           # Your minimal user model
    'AUTO_CREATE_USER': True,            # Create User on first auth (default: True)
    'USER_FIELD_MAPPING': {
        'email': 'email',                # Optional: cache email from JWT
    },
    'UPDATE_USER_ON_AUTH': False,        # Update cached fields on each request

    # JWT Claims
    'ROLE_CLAIM': 'org_role',
    'ORG_CLAIM': 'org_id',
    'PERMISSIONS_CLAIM': 'permissions',
    'METADATA_CLAIM': 'public_metadata',

    # Caching
    'CACHE_PUBLIC_KEYS': True,
    'CACHE_TIMEOUT': 3600,
    'CACHE_KEY_PREFIX': 'clerk_auth',

    # Multi-tenancy
    'ENABLE_ORG_CONTEXT': True,
    'ORG_HEADER': 'X-Organization-ID',

    # Webhooks
    'WEBHOOK_SECRET': 'whsec_...',
    'WEBHOOK_TOLERANCE': 300,
}

Architecture

Pattern 2: Minimal User Model (Recommended)

# Your User model stores ONLY app-specific data
class User(ClerkUser):
    clerk_id = models.CharField(primary_key=True)  # Inherited
    stripe_customer_id = models.CharField(null=True)
    subscription_tier = models.CharField(default='free')

# Clerk stores ALL authentication data:
# - Email, password, name
# - Organization roles and memberships
# - Public/private metadata

# Benefits:
# - Normal Django ForeignKey relationships
# - Single source of truth (Clerk)
# - Automatic user creation on first auth
# - No password management in your app

API Reference

Authentication Classes

  • ClerkAuthentication: DRF authentication class
  • ClerkJWTBackend: Django authentication backend

Permission Classes

  • HasRole(role): Check organization role
  • HasAnyRole(*roles): Check any of the roles
  • HasPermission(permission): Check permission string
  • HasAllPermissions(*permissions): Check all permissions
  • IsOrgMember: Verify org membership
  • IsOrgAdmin: Admin role shortcut

Decorators

  • @require_auth: Require authentication
  • @require_role(role): Require specific role
  • @require_permission(perm): Require permission

Models

  • ClerkUser: Abstract base model for minimal user records

Management Commands

# Sync users from Clerk API
python manage.py sync_clerk_users

# Verify Clerk configuration
python manage.py verify_clerk_setup

Testing

# Run tests
poetry run pytest

# With coverage
poetry run pytest --cov=clerk_auth --cov-report=html

# Type checking
poetry run mypy src/clerk_auth

License

MIT License - see LICENSE file for details.

Links

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

clerk_auth_django-0.1.0.tar.gz (16.1 kB view details)

Uploaded Source

Built Distribution

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

clerk_auth_django-0.1.0-py3-none-any.whl (20.0 kB view details)

Uploaded Python 3

File details

Details for the file clerk_auth_django-0.1.0.tar.gz.

File metadata

  • Download URL: clerk_auth_django-0.1.0.tar.gz
  • Upload date:
  • Size: 16.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.11.13 Linux/6.11.0-1018-azure

File hashes

Hashes for clerk_auth_django-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cba38e9986a2b093eed4f97938ba8f771d1c6dd9326e2096a4ed2b2f7650d914
MD5 a8e47d1468a9e649bc3cae4c50d22388
BLAKE2b-256 862a9528e28781ca9eb6048b6e28594a19bbd71038520f61b271ba0fd8988c00

See more details on using hashes here.

File details

Details for the file clerk_auth_django-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: clerk_auth_django-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 20.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.11.13 Linux/6.11.0-1018-azure

File hashes

Hashes for clerk_auth_django-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 677f670590c1e87c87847475ccd74c2e93a75173917bb98113b308d0a749c8e4
MD5 e0d5a92f9d7496a3160cd83e4692f395
BLAKE2b-256 f9c1cb3c15835899fcaec4aa51e11fdf46de442d851005504c743c124c8777b4

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