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 classClerkJWTBackend: Django authentication backend
Permission Classes
HasRole(role): Check organization roleHasAnyRole(*roles): Check any of the rolesHasPermission(permission): Check permission stringHasAllPermissions(*permissions): Check all permissionsIsOrgMember: Verify org membershipIsOrgAdmin: 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file clerk_auth_django-0.1.1.tar.gz.
File metadata
- Download URL: clerk_auth_django-0.1.1.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c508c89e335b04170c52f93380436668a6f5bed19a816743d48669c2b5627fd0
|
|
| MD5 |
1f0892415fdf8104287c9a9f5c832703
|
|
| BLAKE2b-256 |
470d097810170292f9bcc6eefef5705d859e2f20d098a76b15e766099cee9b67
|
File details
Details for the file clerk_auth_django-0.1.1-py3-none-any.whl.
File metadata
- Download URL: clerk_auth_django-0.1.1-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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
16d0e892345db8037e5bd47aad673c26ccd4741117ac608f7c328cb558d38d51
|
|
| MD5 |
6b868cc440fe8f26ee1a785ee2fb2654
|
|
| BLAKE2b-256 |
2deb1c50addb6667705d5c4f07c23e7952e379974b1c5dc68386d79f3b12a6ee
|