### Install django-descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Install the django-descope package using uv or pip.
```bash
# Using uv
uv add django-descope
# Or using pip
pip install django-descope
```
--------------------------------
### Install django-descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/README.md
Install the django-descope package using pip.
```bash
pip install django-descope
```
--------------------------------
### Install django-descope
Source: https://github.com/descope/django-descope/blob/main/README.md
Install the django-descope package using pip or uv. Add 'django_descope' to your INSTALLED_APPS setting.
```bash
uv add django-descope
```
```bash
pip install django-descope
```
```python
INSTALLED_APPS = [
...
'django_descope',
]
```
--------------------------------
### Configuration Priority Example
Source: https://github.com/descope/django-descope/blob/main/_autodocs/configuration.md
Illustrates the order of precedence for configuration settings: Django settings, environment variables, and then hardcoded defaults.
```python
# Priority 1 (highest): Django settings.py
DESCOPE_PROJECT_ID = "myproject123"
# Priority 2: Environment variables
export DESCOPE_PROJECT_ID=myproject456
# Priority 3 (lowest): Hardcoded defaults (if applicable)
# None for DESCOPE_PROJECT_ID (required)
```
--------------------------------
### Example Project ID Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/configuration.md
Shows how to set the required `DESCOPE_PROJECT_ID` either in Django's `settings.py` or via an environment variable.
```python
# In settings.py
DESCOPE_PROJECT_ID = "abcd1234ef5678"
# OR via environment variable
export DESCOPE_PROJECT_ID=abcd1234ef5678
```
--------------------------------
### Debug Output Example
Source: https://github.com/descope/django-descope/blob/main/_autodocs/errors.md
Example of the detailed debug messages you might see in the console when Descope's debug logging is enabled.
```text
DEBUG:django_descope.authentication:Validating (and refreshing) Descope session
DEBUG:django_descope.authentication:{'dsSessionJwt': {'jwt': '...', 'claims': {...}}, 'dsRefreshToken': {...}}
```
--------------------------------
### Configure Django Logout View
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
This example shows how to configure a standard Django LogoutView in your `urls.py` file to handle user logouts.
```python
# In urls.py
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('logout/', LogoutView.as_view(), name='logout'),
]
```
--------------------------------
### Standard Django Descope URL Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Example of standard integration of django-descope URLs with a base path of 'auth/'.
```python
path('auth/', include('django_descope.urls'))
```
--------------------------------
### Manual DescopeUser Synchronization Example
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/models.md
Demonstrates how to manually synchronize a DescopeUser object with Descope session and refresh tokens if needed, outside of the automatic authentication flow.
```python
from django_descope.models import DescopeUser
user = DescopeUser.objects.get(username="user123")
user.sync(validated_session, refresh_token)
```
--------------------------------
### Complete HTML Structure for Descope Integration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/templatetags.md
An example demonstrating the full HTML structure including the script tag for the web component, the component element itself, and the JavaScript for handling authentication success.
```html
```
--------------------------------
### Complete Django Settings Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
Example of a complete Django settings.py file demonstrating how to configure Descope, including required and optional settings, and integration with Django's core components.
```python
import os
# Required
DESCOPE_PROJECT_ID = os.environ.get(
"DESCOPE_PROJECT_ID",
"dev_project_id" # Fallback for development
)
# Optional - API key for test user management
DESCOPE_MANAGEMENT_KEY = os.environ.get("DESCOPE_MANAGEMENT_KEY")
# Optional - customize role names if needed
DESCOPE_IS_STAFF_ROLE = "django_staff"
DESCOPE_IS_SUPERUSER_ROLE = "django_admin"
# Optional - use different claim as username if needed
DESCOPE_USERNAME_CLAIM = "userId" # Instead of "sub"
# Django settings
INSTALLED_APPS = [
# ...
'django_descope',
]
MIDDLEWARE = [
# ...
'django_descope.middleware.DescopeMiddleware',
]
AUTHENTICATION_BACKENDS = [
'django_descope.authentication.DescopeAuthentication',
]
```
--------------------------------
### Usage Example for Django Descope Authentication
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/authentication.md
Demonstrates how to use the `authenticate` function within a Django view or middleware to log in a user with a Descope token. Ensure `django.contrib.auth.login` is imported.
```python
from django.contrib.auth import authenticate
# In a view or middleware
user = authenticate(request)
if user:
# User is authenticated
login(request, user)
else:
# User is not authenticated
pass
```
--------------------------------
### Root Path Configuration for Django Descope URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Example of integrating django-descope URLs at the root of the project, making endpoints directly accessible.
```python
path('', include('django_descope.urls'))
```
--------------------------------
### Custom Base Path for Django Descope URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Example of integrating django-descope URLs with a custom base path, such as 'api/auth/'.
```python
path('api/auth/', include('django_descope.urls'))
```
--------------------------------
### Referencing Store JWT URL in Django Templates
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Example of how to reference the 'store_jwt' URL using Django's template tag syntax with the app namespace.
```html
Store Token
```
--------------------------------
### Get User Profile
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Retrieves the user's profile information using a valid refresh token. Ensure the `refresh_token` is correctly passed.
```python
from django_descope import descope_client
# Get user profile (requires valid refresh token)
user_info = descope_client.me(refresh_token)
```
--------------------------------
### Django Descope URL Reversing in Templates
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Example of using the `url` template tag to dynamically generate the action URL for a form submission to the 'store_jwt' endpoint.
```html
```
--------------------------------
### DescopeUser Get Username Method
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/models.md
Returns the username of the DescopeUser instance, which is typically the Descope user ID.
```python
def get_username(self) -> str:
# ... method implementation ...
```
--------------------------------
### Initialize Descope Client
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Instantiate the DescopeClient using project ID and an optional management key from Django settings.
```python
descope_client = DescopeClient(
project_id=settings.DESCOPE_PROJECT_ID, # Required
management_key=settings.DESCOPE_MANAGEMENT_KEY, # Optional
)
```
--------------------------------
### Utility Functions and Instance
Source: https://github.com/descope/django-descope/blob/main/_autodocs/START_HERE.md
Information on utility functions and the global Descope SDK client instance available for use.
```APIDOC
## Functions and Instance
### add_tokens_to_request()
**Description**: A utility function to add Descope tokens to an outgoing request.
### descope_flow (template tag)
**Description**: A Django template tag used to embed Descope authentication flows within HTML templates.
### descope_client
**Description**: The global Descope SDK client instance, providing access to Descope's management API.
```
--------------------------------
### Import Django MiddlewareMixin
Source: https://github.com/descope/django-descope/blob/main/_autodocs/types.md
Import Django's modern middleware base class. Custom middleware should extend this class.
```python
from django.utils.deprecation import MiddlewareMixin
```
--------------------------------
### Import Django BaseBackend
Source: https://github.com/descope/django-descope/blob/main/_autodocs/types.md
Import Django's authentication backend base class. Custom authentication backends should extend this class.
```python
from django.contrib.auth.backends import BaseBackend
```
--------------------------------
### Configure Django Settings
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Add 'django_descope' to INSTALLED_APPS and include DescopeMiddleware in your MIDDLEWARE settings. Ensure DESCOPE_PROJECT_ID is set.
```python
import os
INSTALLED_APPS = [
# ... other apps
'django_descope',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ... other middleware
'django_descope.middleware.DescopeMiddleware', # Add after auth middleware
]
# Required: Your Descope project ID
DESCOPE_PROJECT_ID = os.environ.get("DESCOPE_PROJECT_ID")
```
--------------------------------
### Get User Profile
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Retrieves the profile information for the authenticated user using a refresh token. Returns a dictionary containing user profile details.
```APIDOC
## Get User Profile
### Description
Retrieves the profile information for the authenticated user using a refresh token. Returns a dictionary containing user profile details.
### Method Signature
`descope_client.me(refresh_token: str)`
### Parameters
- **refresh_token** (str) - The refresh token to authenticate the request.
### Returns
A dictionary with user profile information.
```
--------------------------------
### Create Test User with Roles
Source: https://github.com/descope/django-descope/blob/main/_autodocs/README.md
Use this utility to create a test user with specified roles and email verification status. This is useful for setting up testing environments.
```python
from django_descope import descope_client
from descope import DeliveryMethod
# Create test user
descope_client.mgmt.user.create_test_user(
"test@example.com",
role_names=["is_staff"],
verified_email=True,
)
```
--------------------------------
### Import Descope Client Instance
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Import the globally initialized DescopeClient instance for token validation and role checking.
```python
from django_descope import descope_client
# Use for token validation, role checking, etc.
```
--------------------------------
### Get Authenticated User Profile
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Retrieve the profile information for the currently authenticated user using their refresh token. This method returns a dictionary containing user details.
```python
# Get authenticated user's profile
profile = descope_client.me(refresh_token: str)
```
--------------------------------
### Constructor for DescopeAuthentication
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/authentication.md
Initializes the Descope authentication backend. It inherits from Django's `BaseBackend`.
```python
def __init__(self, *args, **kwargs)
```
--------------------------------
### Custom Redirect After Sign-Up with Descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/templatetags.md
This snippet implements a custom redirect after a user completes the sign-up process. If the user is not authenticated, it displays the Descope sign-up flow, redirecting to '/onboarding/' upon successful completion.
```html
{% load descope %}
{% if not user.is_authenticated %}
Complete Your Signup
{% descope_flow "sign-up" "/onboarding/" %}
{% endif %}
```
--------------------------------
### Get User Profile in Django View
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Retrieves and returns the user's Descope profile in a Django view if the user is authenticated. Handles potential exceptions during the profile retrieval process.
```python
from django_descope import descope_client
def get_user_profile(request):
user = request.user
if user.is_authenticated:
try:
profile = descope_client.me(user.refresh_token)
return JsonResponse(profile)
except Exception as e:
return JsonResponse({"error": str(e)}, status=400)
```
--------------------------------
### Import Descope Client
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Import the Descope client for interacting with the Descope API. This is the primary entry point for SDK functionality.
```python
from descope import DescopeClient
```
--------------------------------
### Add Descope Tokens to Django Session
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/authentication.md
Stores Descope session and refresh tokens in the Django session object. This is typically used after receiving tokens from Descope, for example, in a callback view. The tokens are then persisted to the database via the session backend.
```python
from django.contrib.auth import authenticate
from django_descope.authentication import add_tokens_to_request
# After receiving tokens from Descope (e.g., in a callback view)
add_tokens_to_request(
request.session,
session_token="eyJ0eXAiOiJKV1QiLC...",
refresh_token="eyJ0eXAiOiJKV1QiLC..."
)
# User can now authenticate on subsequent requests
```
--------------------------------
### DescopeMiddleware Constructor
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/middleware.md
Initializes the DescopeMiddleware with the next response handler in the Django pipeline.
```python
def __init__(self, get_response)
```
--------------------------------
### Descope Client Initialization
Source: https://github.com/descope/django-descope/blob/main/_autodocs/configuration.md
Initializes the global DescopeClient using project ID and management key from Django settings. This client is used for various Descope operations like token validation and user profile retrieval.
```python
from descope import DescopeClient
from django_descope.conf import settings
descope_client = DescopeClient(
project_id=settings.DESCOPE_PROJECT_ID,
management_key=settings.DESCOPE_MANAGEMENT_KEY,
)
```
--------------------------------
### Descope Client Initialization and Lifecycle
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
The DescopeClient is initialized once upon module import and persists throughout the application's lifetime. Configuration is loaded from Django settings and environment variables.
```python
# Module Import:
from django_descope import descope_client
# Client Creation:
# DescopeClient is instantiated with project ID and management key
# Configuration Load:
# Settings are read from Django settings and environment variables
# Validation:
# If DESCOPE_PROJECT_ID is not set, ImproperlyConfigured is raised
# Application Lifetime:
# Client remains in memory and is reused for all operations
# The client is not recreated on each request; it's a singleton managed by the module system.
```
--------------------------------
### Django Settings Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Include 'django_descope' in INSTALLED_APPS and add DescopeMiddleware to your MIDDLEWARE settings. Set your DESCOPE_PROJECT_ID.
```python
INSTALLED_APPS = [
# ...
'django_descope',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ...
'django_descope.middleware.DescopeMiddleware',
]
DESCOPE_PROJECT_ID = "your_project_id"
```
--------------------------------
### Using Descope Flow Template Tag
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Demonstrates the usage of the `descope_flow` template tag to automatically generate the correct URL for the 'store_jwt' endpoint.
```html
{% load descope %}
{% descope_flow "sign-up-or-in" "/dashboard/" %}
```
--------------------------------
### DescopeMiddleware Constructor
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/middleware.md
Initializes the DescopeMiddleware with the next response handler in the Django request pipeline.
```APIDOC
## DescopeMiddleware Constructor
### Description
Initializes the middleware with a response handler function.
### Method
`__init__`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
None
### Throws
Does not explicitly raise exceptions.
```
--------------------------------
### Basic Sign-Up/Sign-In Flow with Descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/templatetags.md
Use this snippet to embed a Descope sign-up or sign-in flow directly into your Django template. It conditionally displays a welcome message for authenticated users or the Descope flow for others, redirecting to '/dashboard/' upon success.
```html
{% load descope %}
Login
{% if user.is_authenticated %}
Welcome {{ user.email }}
Log Out
{% else %}
Sign In or Sign Up
{% descope_flow "sign-up-or-in" "/dashboard/" %}
{% endif %}
```
--------------------------------
### Module-Level Settings Instance
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
A global instance of the Settings class is created at module import time and automatically validated during Django startup. Access configuration values like project ID, staff role, and username claim.
```python
settings = Settings()
ssettings.validate()
```
```python
from django_descope.conf import settings
# Access configuration
project_id = settings.DESCOPE_PROJECT_ID
staff_role = settings.DESCOPE_IS_STAFF_ROLE
username_claim = settings.DESCOPE_USERNAME_CLAIM
```
--------------------------------
### Load and Use Descope Template Tag
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Load the Descope template tags and use the `descope_flow` tag within your templates to initiate the authentication process.
```html
{% load descope %}
{% if not user.is_authenticated %}
{% descope_flow "sign-up-or-in" "/dashboard/" %}
{% endif %}
```
--------------------------------
### Create Test User
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Creates a test user with the specified login ID and optional role names. The user's email can be marked as verified.
```APIDOC
## Create Test User
### Description
Creates a test user with the specified login ID and optional role names. The user's email can be marked as verified.
### Method Signature
`descope_client.mgmt.user.create_test_user(login_id: str, role_names: list[str] = None, verified_email: bool = False)`
### Parameters
- **login_id** (str) - The login ID for the new test user.
- **role_names** (list[str], optional) - A list of role names to assign to the user. Defaults to None.
- **verified_email** (bool, optional) - Whether to mark the user's email as verified. Defaults to False.
```
--------------------------------
### Test Authenticated Requests with Descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
This snippet demonstrates how to create a test user, generate an OTP, verify it, and add authentication tokens to a Django test client session for testing authenticated requests. It also includes cleanup.
```python
from django_descope import descope_client
from django_descope.authentication import add_tokens_to_request
from descope import DeliveryMethod
# Create a test user
login_id = "test@example.com"
descope_client.mgmt.user.create_test_user(
login_id,
role_names=["is_staff"],
verified_email=True,
)
# Generate OTP for test user
resp = descope_client.mgmt.user.generate_otp_for_test_user(
DeliveryMethod.EMAIL,
login_id,
)
# Get tokens by verifying OTP
token = descope_client.otp.verify_code(
DeliveryMethod.EMAIL,
login_id,
resp.get("code")
)
# Add tokens to test client session
session = client.session
add_tokens_to_request(
session,
token[SESSION_TOKEN_NAME]["jwt"],
token[REFRESH_SESSION_TOKEN_NAME]["jwt"],
)
# Clean up
descope_client.mgmt.user.delete(login_id)
```
--------------------------------
### Create Test User
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Create a temporary test user for development or testing purposes. You can specify the user's login ID and optionally assign roles and set email verification status.
```python
# Create test user
descope_client.mgmt.user.create_test_user(
login_id: str,
role_names: list[str] = None,
verified_email: bool = False,
)
```
--------------------------------
### Descope Web Component Initialization
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/templatetags.md
The `descope_flow` tag includes the Descope web component script from a CDN. This is typically done only once on the first invocation.
```html
```
--------------------------------
### Django Settings Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Configure Descope project ID and management key in Django's settings.py or via environment variables.
```python
# settings.py
DESCOPE_PROJECT_ID = "my_project"
DESCOPE_MANAGEMENT_KEY = "my_api_key"
# OR environment variables
export DESCOPE_PROJECT_ID=my_project
export DESCOPE_MANAGEMENT_KEY=my_api_key
```
--------------------------------
### Configure Project URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Include the django_descope URLs in your project's main urls.py to handle Descope authentication endpoints.
```python
from django.urls import path, include
urlpatterns = [
# ... other patterns
path('auth/', include('django_descope.urls')),
]
```
--------------------------------
### Django Descope File Structure
Source: https://github.com/descope/django-descope/blob/main/_autodocs/README.md
Illustrates the directory and file organization of the django-descope project. This structure helps in understanding the placement of different components like authentication, middleware, and template tags.
```text
django_descope/
├── __init__.py # Package initialization, descope_client
├── apps.py # Django app config
├── conf.py # Settings and configuration
├── authentication.py # Authentication backend
├── middleware.py # Request middleware
├── models.py # DescopeUser model
├── views.py # HTTP views
├── urls.py # URL routing
├── migrations/ # Database migrations
│ └── 0001_initial.py
└── templatetags/
├── __init__.py
└── descope.py # Template tags
```
--------------------------------
### Include Descope URLs
Source: https://github.com/descope/django-descope/blob/main/README.md
Include the descope URL patterns in your project's main urls.py file. This makes Descope's authentication routes available.
```python
path('auth/', include('django_descope.urls')),
```
--------------------------------
### Access Descope Settings
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Access the global settings instance to retrieve Descope configuration values like project ID.
```python
from django_descope.conf import settings
project_id = settings.DESCOPE_PROJECT_ID
```
--------------------------------
### Import Django User/AbstractUser
Source: https://github.com/descope/django-descope/blob/main/_autodocs/types.md
Import Django's user model. DescopeUser is a proxy model that inherits from this, sharing the same database table.
```python
from django.contrib.auth.models import User
# or
from django.contrib.auth import get_user_model
User = get_user_model()
```
--------------------------------
### Integrating django-descope URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Demonstrates how to include the django-descope URL patterns into your main Django project's `urls.py` file. The base path can be customized.
```APIDOC
```python
# urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('django_descope.urls')), # This line
# Other patterns...
]
```
This configuration maps the `store_jwt` endpoint to `POST /auth/store_jwt`.
```
--------------------------------
### Minimal Django Settings
Source: https://github.com/descope/django-descope/blob/main/_autodocs/README.md
Configure Django settings to include django-descope and set your Descope Project ID.
```python
# settings.py
INSTALLED_APPS = ['django_descope']
MIDDLEWARE = ['django_descope.middleware.DescopeMiddleware']
DESCOPE_PROJECT_ID = "your_project_id"
```
--------------------------------
### URL Reversing in Templates
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Shows how to use Django's template tags to dynamically generate the URL for the `store_jwt` endpoint, ensuring correct routing.
```APIDOC
{% load descope %}
```
--------------------------------
### Integrating Django Descope URLs into Project URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Shows how to include the django-descope URL configuration into your main Django project's `urls.py` file.
```python
# urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('django_descope.urls')), # This line
# Other patterns...
]
```
--------------------------------
### Import Django HttpResponse
Source: https://github.com/descope/django-descope/blob/main/_autodocs/types.md
Import Django's HTTP response object. This is the base class for all HTTP responses.
```python
from django.http import HttpResponse
```
--------------------------------
### Configure Descope Authentication Backend
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Configure Django's authentication backends to use DescopeAuthentication for validating Descope JWT tokens.
```python
from django_descope.authentication import DescopeAuthentication, add_tokens_to_request
# In settings.py
AUTHENTICATION_BACKENDS = ['django_descope.authentication.DescopeAuthentication']
# Or use via middleware (recommended)
```
--------------------------------
### Configure Django URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/README.md
Include django-descope's URLs in your project's urlpatterns.
```python
# urls.py
urlpatterns = [path('auth/', include('django_descope.urls'))]
```
--------------------------------
### validate Method Usage
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
Shows how to manually call the validate method to check for required configuration, such as DESCOPE_PROJECT_ID. This validation is also performed automatically on module import.
```python
from django_descope.conf import settings
from django.core.exceptions import ImproperlyConfigured
# This is called automatically, but can be called manually for testing
try:
settings.validate()
except ImproperlyConfigured as e:
print(f"Configuration error: {e}")
```
--------------------------------
### Accessing Settings in Django Code
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
Demonstrates how to access Descope settings within a Django project after overriding a setting in `settings.py`.
```python
# settings.py
DESCOPE_PROJECT_ID = "override_value"
# Access in code
from django_descope.conf import settings
project_id = settings.DESCOPE_PROJECT_ID # Returns "override_value"
```
--------------------------------
### Django Authentication Backend Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/authentication.md
Add the Descope authentication backend to your Django settings to enable Descope-based authentication.
```python
AUTHENTICATION_BACKENDS = [
'django_descope.authentication.DescopeAuthentication',
]
```
--------------------------------
### validate Method
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
Validates that all required configuration settings, specifically DESCOPE_PROJECT_ID, are present and properly set. This method is called automatically during module initialization.
```APIDOC
## Method: validate
```python
def validate(self) -> None
```
Validates that all required configuration is present and properly set.
**Throws:** `ImproperlyConfigured` if validation fails
**Validation Rules:**
1. `DESCOPE_PROJECT_ID` must be set and non-empty
**Called Automatically:** During module initialization (at import time) when `django_descope` is imported.
**Usage Example:**
```python
from django_descope.conf import settings
# This is called automatically, but can be called manually for testing
try:
settings.validate()
except ImproperlyConfigured as e:
print(f"Configuration error: {e}")
```
```
--------------------------------
### Enable Debug Logging for Descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/errors.md
Configure Django's logging settings in `settings.py` to enable DEBUG level logging for Descope's authentication and middleware components.
```python
# In settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django_descope.authentication': {
'handlers': ['console'],
'level': 'DEBUG',
},
'django_descope.middleware': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
```
--------------------------------
### Set Environment Variable
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Export your Descope project ID as an environment variable. Obtain your project ID from the Descope Console.
```bash
export DESCOPE_PROJECT_ID="your_project_id"
```
--------------------------------
### Django Descope URL Reversing in Python Code
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Illustrates how to reverse the 'store_jwt' URL in Python code to obtain its absolute path or use it in redirects.
```python
from django.urls import reverse
# Get the absolute path
store_jwt_url = reverse('django_descope:store_jwt')
# Returns: '/auth/store_jwt' (depending on configuration)
# Use in response
return redirect(reverse('django_descope:store_jwt'))
```
--------------------------------
### Sign-In Only Flow with Descope
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/templatetags.md
Use this snippet for a dedicated sign-in flow. It embeds the Descope sign-in UI and redirects the user to '/auth-confirmed/' once the authentication is successful.
```html
{% load descope %}
{% descope_flow "sign-in" "/auth-confirmed/" %}
```
--------------------------------
### Django Descope Project File Structure
Source: https://github.com/descope/django-descope/blob/main/_autodocs/INDEX.md
Overview of the directory structure for the Django Descope project, indicating the location of Python modules and migration files.
```text
django_descope/
├── __init__.py → api-reference/init.md
├── apps.py → api-reference/apps.md
├── conf.py → api-reference/conf.md
├── authentication.py → api-reference/authentication.md
├── middleware.py → api-reference/middleware.md
├── models.py → api-reference/models.md
├── views.py → api-reference/views.md
├── urls.py → api-reference/urls.md
├── migrations/
│ └── 0001_initial.py
└── templatetags/
├── __init__.py
└── descope.py → api-reference/templatetags.md
```
--------------------------------
### Django Descope Store JWT URL Pattern Details
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/urls.md
Details the components of the 'store_jwt' URL pattern, including route, view, name, and HTTP method.
```python
path("store_jwt", views.StoreJwt.as_view(), name="store_jwt")
```
--------------------------------
### Settings Class Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
The Settings class manages Descope integration configuration with a hierarchical resolution system, prioritizing Django settings, then environment variables, and finally class defaults.
```APIDOC
## Configuration Attributes
### DESCOPE_PROJECT_ID
**Type:** `str | None`
**Required:** Yes
**Environment Variable:** `DESCOPE_PROJECT_ID`
**Django Setting:** `DESCOPE_PROJECT_ID`
The unique identifier for your Descope project, obtained from the Descope Console. Must be set; raises `ImproperlyConfigured` if empty or None.
### DESCOPE_MANAGEMENT_KEY
**Type:** `str | None`
**Required:** No
**Default:** `None`
**Environment Variable:** `DESCOPE_MANAGEMENT_KEY`
**Django Setting:** `DESCOPE_MANAGEMENT_KEY`
The management API key for Descope. Required only for management API operations like creating test users.
### DESCOPE_IS_STAFF_ROLE
**Type:** `str`
**Required:** No
**Default:** `"is_staff"`
**Environment Variable:** Not supported; use Django setting
**Django Setting:** `DESCOPE_IS_STAFF_ROLE`
The Descope role name that maps to Django's `is_staff` attribute. Users with this role will have staff access to Django admin.
### DESCOPE_IS_SUPERUSER_ROLE
**Type:** `str`
**Required:** No
**Default:** `"is_superuser"`
**Environment Variable:** Not supported; use Django setting
**Django Setting:** `DESCOPE_IS_SUPERUSER_ROLE`
The Descope role name that maps to Django's `is_superuser` attribute. Users with this role will have superuser access.
### DESCOPE_USERNAME_CLAIM
**Type:** `str`
**Required:** No
**Default:** `"sub"`
**Environment Variable:** Not supported; use Django setting
**Django Setting:** `DESCOPE_USERNAME_CLAIM`
The JWT claim to use as the Django username. Must be unique per user to prevent account takeovers.
### DESCOPE_WEB_COMPONENT_VERSION
**Type:** `str`
**Default:** `"3.69.1"` (updated by Renovate)
**Note:** This is a hardcoded default; set `DESCOPE_WEB_COMPONENT_SRC` directly to override.
The version of the Descope web component library to use. Automatically managed by Renovate for security and feature updates.
### DESCOPE_WEB_COMPONENT_SRC
**Type:** `str`
**Default:** CDN URL from unpkg.com
**Note:** Read-only; computed from `DESCOPE_WEB_COMPONENT_VERSION`.
The full URL to the Descope web component JavaScript file, loaded in templates via the `descope_flow` tag.
```
--------------------------------
### Registering django-descope in INSTALLED_APPS
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/apps.md
To enable the django-descope app and its features, add 'django_descope' to your Django project's `INSTALLED_APPS` setting.
```python
# In settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# ...
'django_descope', # Registers DescopeConfig
]
```
--------------------------------
### Custom Descope Base URI Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/configuration.md
Configure the base URI for custom Descope deployments or testing environments. This can be set directly in settings.py or via an environment variable.
```python
# In settings.py (rarely needed)
# For custom Descope deployment
DESCOPE_BASE_URI = "https://custom-descope.example.com"
# OR via environment variable
export DESCOPE_BASE_URI=https://custom-descope.example.com
```
--------------------------------
### Configure Descope Middleware in Django Settings
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Ensure the DescopeMiddleware is correctly added to your Django settings.py file. It must be placed after the AuthenticationMiddleware.
```python
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ... other middleware
'django_descope.middleware.DescopeMiddleware', # Must be after auth middleware
]
```
--------------------------------
### Generate OTP for Test User
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Generate a One-Time Password (OTP) for a test user, which can be used for OTP-based authentication flows. Specify the delivery method and the user's login ID.
```python
# Generate OTP for test user
descope_client.mgmt.user.generate_otp_for_test_user(
delivery_method: DeliveryMethod,
login_id: str,
)
```
--------------------------------
### DescopeUser.__str__ Method
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/models.md
Returns a string representation of the DescopeUser object, formatted as 'DescopeUser {username}'.
```APIDOC
### Method: __str__
```python
def __str__(self) -> str
```
Returns a string representation of the user.
**Return Type:** `str` — Format: `"DescopeUser {username}"`
```
--------------------------------
### Use DescopeUser Model
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Interact with the DescopeUser proxy model to access user data synced from Descope, including email and mapped roles.
```python
from django_descope.models import DescopeUser
user = DescopeUser.objects.get(username="user123")
print(user.email) # Descope email
print(user.is_staff) # From DESCOPE_IS_STAFF_ROLE
```
--------------------------------
### Include Descope URLs
Source: https://github.com/descope/django-descope/blob/main/_autodocs/module-overview.md
Include the Descope application's URLs in your project's main URL configuration to enable endpoints like the JWT token storage.
```python
# In project urls.py
from django.urls import path, include
urlpatterns = [
path('auth/', include('django_descope.urls')),
]
```
--------------------------------
### Generate OTP for Test User
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Generates an One-Time Password (OTP) for a test user via email. The response contains the OTP code, which can be used for verification.
```python
from django_descope import descope_client
from descope import DeliveryMethod
# Generate OTP for test user
resp = descope_client.mgmt.user.generate_otp_for_test_user(
DeliveryMethod.EMAIL,
"test@example.com",
)
```
--------------------------------
### Import Django HttpRequest
Source: https://github.com/descope/django-descope/blob/main/_autodocs/types.md
Import Django's HTTP request object. This object contains session data, POST data, cookies, and more.
```python
from django.http import HttpRequest
```
--------------------------------
### Configure Descope Management Key
Source: https://github.com/descope/django-descope/blob/main/_autodocs/configuration.md
Set the DESCOPE_MANAGEMENT_KEY for Descope management APIs. Use Django settings for local development and environment variables for production.
```python
# In settings.py (recommended for local development only)
DESCOPE_MANAGEMENT_KEY = "super_secret_key_xyz"
```
```bash
# OR via environment variable (recommended for production)
export DESCOPE_MANAGEMENT_KEY=super_secret_key_xyz
```
--------------------------------
### Configure Descope Middleware
Source: https://github.com/descope/django-descope/blob/main/README.md
Add the DescopeMiddleware to your Django project's MIDDLEWARE setting. Ensure it is placed after AuthenticationMiddleware and SessionMiddleware.
```python
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
'django_descope.middleware.DescopeMiddleware',
]
```
--------------------------------
### Import Django HttpResponseBadRequest
Source: https://github.com/descope/django-descope/blob/main/_autodocs/types.md
Import Django's response subclass for HTTP 400 Bad Request errors. Used to indicate client-side errors.
```python
from django.http import HttpResponseBadRequest
```
--------------------------------
### Validate and Refresh Session Tokens
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/init.md
Use this method to validate existing session and refresh tokens and obtain updated tokens and claims. It ensures the session is still valid and refreshes tokens if necessary.
```python
# Validate and refresh session tokens
validated_session = descope_client.validate_and_refresh_session(
session_token: str,
refresh_token: str
)
```
--------------------------------
### DescopeUser String Representation
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/models.md
Provides a string representation for the DescopeUser model, formatted as 'DescopeUser {username}'.
```python
def __str__(self) -> str:
# ... method implementation ...
```
--------------------------------
### Custom Redirect After Descope Login
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Use the `descope_flow` template tag to specify a custom URL path for redirecting users after a successful login or sign-up.
```html
{% descope_flow "sign-up-or-in" "/dashboard/" %}
```
--------------------------------
### DESCOPE_WEB_COMPONENT_VERSION Default
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
Specifies the default version of the Descope web component library. This value is automatically managed by Renovate for updates.
```python
DESCOPE_WEB_COMPONENT_VERSION = "3.69.1"
```
--------------------------------
### DescopeMiddleware Call Method
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/middleware.md
Processes an incoming HTTP request, attempting to authenticate the user via Descope credentials stored in the session.
```python
def __call__(self, request: HttpRequest) -> HttpResponse
```
--------------------------------
### Django Middleware Configuration
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/authentication.md
Include the Descope middleware in your Django settings to automatically handle authentication.
```python
MIDDLEWARE = [
# ...
'django_descope.middleware.DescopeMiddleware',
]
```
--------------------------------
### App Name Property
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/apps.md
The `name` property specifies the application name. Django uses this to identify the app within `INSTALLED_APPS` and for app-specific functionalities.
```python
name = "django_descope"
```
--------------------------------
### Django View Logic for Token Storage
Source: https://github.com/descope/django-descope/blob/main/_autodocs/errors.md
This Python code snippet illustrates the logic within the `StoreJwt.post()` method that checks for the presence of session and refresh tokens. If either is missing or empty, it returns an `HttpResponseBadRequest`.
```python
session = request.POST.get(SESSION_COOKIE_NAME)
refresh = request.COOKIES.get(REFRESH_SESSION_COOKIE_NAME)
if not refresh:
refresh = request.POST.get(REFRESH_SESSION_COOKIE_NAME)
if session and refresh:
# Success (200)
else:
# Error (400)
return HttpResponseBadRequest()
```
--------------------------------
### __getattribute__ Method Implementation
Source: https://github.com/descope/django-descope/blob/main/_autodocs/api-reference/conf.md
Overrides attribute access to implement a three-level configuration hierarchy: Django settings, environment variables, and class defaults.
```python
def __getattribute__(self, name: str) -> Any:
"""Overrides attribute access to implement configuration hierarchy."""
# Implementation details are omitted in the source, but the description explains the logic.
pass
```
--------------------------------
### Implement Login Page with Descope Flow
Source: https://github.com/descope/django-descope/blob/main/_autodocs/quick-start.md
Use the 'descope_flow' template tag to embed the Descope authentication component in your Django templates. This tag handles the display of the login/signup interface.
```html
{% extends "base.html" %}
{% load descope %}
{% block content %}
{% if user.is_authenticated %}
Welcome {{ user.email }}!
Log Out
{% else %}
Sign In or Sign Up
{% descope_flow "sign-up-or-in" "/" %}
{% endif %}
{% endblock %}
```