### Run WebAuthn Example App Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Builds and runs a WebAuthn-enabled example application using the provided Makefile command. This is useful for testing WebAuthn functionality. ```bash $ make example-webauthn ``` -------------------------------- ### Install django-otp-yubikey Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/installation.rst Installs the django-otp-yubikey plugin to enable YubiKey support for two-factor authentication. ```console pip install django-otp-yubikey ``` -------------------------------- ### Twilio Gateway Setup Source: https://django-two-factor-auth.readthedocs.io/en/stable/configuration Instructions for installing the Twilio client, adding necessary URLs, and configuring middleware for the Twilio gateway. ```APIDOC ## Twilio Gateway Setup ### Description This section outlines the steps required to integrate the Twilio gateway for sending verification codes via SMS and phone calls. ### Installation Install the Twilio client library: ```bash $ pip install twilio ``` ### URL Configuration Add the Twilio gateway URLs to your project's `urls.py`: ```python # urls.py from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_urls urlpatterns = [ path('', include(tf_twilio_urls)), ... ] ``` ### Middleware Configuration Ensure the `ThreadLocals` middleware and `OTPMiddleware` are included in your `MIDDLEWARE` settings: ```python MIDDLEWARE = ( ... # Always include for two-factor auth 'django_otp.middleware.OTPMiddleware', # Include for Twilio gateway 'two_factor.middleware.threadlocals.ThreadLocals', ) ``` ### Twilio Gateway Configuration Configure your Twilio credentials and settings in your Django settings file: - **`TWILIO_ACCOUNT_SID`** (string): Your Twilio Account SID. - **`TWILIO_AUTH_TOKEN`** (string): Your Twilio authorization token. - **`TWILIO_CALLER_ID`** (string): A verified Twilio phone number to use as the caller ID for SMS and calls. - **`TWILIO_MESSAGING_SERVICE_SID`** (string, Optional): A Twilio Messaging Service SID. If provided, Twilio will use this service for sending SMS, which can manage multiple numbers. If not provided, `TWILIO_CALLER_ID` will be used. ### Request Example No direct API request examples for setup, configuration is done via Django settings. ### Response No direct API response examples for setup, configuration is done via Django settings. ``` -------------------------------- ### Install django-two-factor-auth with phonenumber extras Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/installation.rst Installs django-two-factor-auth with optional phonenumber support, requiring either the 'phonenumbers' or 'phonenumberslite' package. ```console pip install django-two-factor-auth[phonenumbers] ``` ```console pip install django-two-factor-auth[phonenumberslite] ``` -------------------------------- ### Install django-otp-yubikey Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Installs the django-otp-yubikey package, which is required for YubiKey support. ```bash $ pip install django-otp-yubikey ``` -------------------------------- ### Install django-two-factor-auth Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Installs the django-two-factor-auth package and its core dependencies using pip. ```bash $ pip install django-two-factor-auth ``` -------------------------------- ### Fake Gateway Setup Source: https://django-two-factor-auth.readthedocs.io/en/stable/configuration Instructions for setting up the Fake gateway for local development, which logs verification tokens instead of sending them. ```APIDOC ## Fake Gateway Setup ### Description The Fake gateway is useful for local development as it prints verification tokens to the logger instead of sending them via SMS or calls. ### Configuration To see the tokens, you need to configure your Django logging to set the log level for the `two_factor` logger to `INFO`. ```python LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'two_factor': { 'handlers': ['console'], 'level': 'INFO', } } } ``` ### Usage When the Fake gateway is active, any attempt to send a verification token will result in the token being logged at the `INFO` level for the `two_factor` logger. ### Request Example No direct API request examples for setup, configuration is done via Django settings. ### Response No direct API response examples for setup, configuration is done via Django settings. ``` -------------------------------- ### Install django-two-factor-auth with WebAuthn Extra Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Installs django-two-factor-auth along with the 'webauthn' extra, which includes the py_webauthn package for WebAuthn device support. ```bash $ pip install django-two-factor-auth[webauthn] ``` -------------------------------- ### Install django-two-factor-auth with Phonenumberslite Extra Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Installs django-two-factor-auth along with the 'phonenumberslite' extra, which includes the phonenumberslite library for phone number capabilities. ```bash $ pip install django-two-factor-auth[phonenumberslite] ``` -------------------------------- ### Configure WebAuthn plugin in INSTALLED_APPS Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/installation.rst Adds the 'two_factor.plugins.webauthn' app to the Django project's INSTALLED_APPS setting to enable WebAuthn authentication. ```python INSTALLED_APPS = [ ... 'two_factor.plugins.webauthn', ] ``` -------------------------------- ### Install django-two-factor-auth with Phonenumbers Extra Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Installs django-two-factor-auth along with the 'phonenumbers' extra, which includes the phonenumbers library for phone number capabilities. ```bash $ pip install django-two-factor-auth[phonenumbers] ``` -------------------------------- ### Install Twilio Client for Two-Factor Auth Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/configuration.rst Instructions to install the Twilio client library, a dependency for using the Twilio gateway with Django Two-Factor Authentication. This is a prerequisite for enabling SMS and phone call authentication methods via Twilio. ```console pip install twilio ``` -------------------------------- ### Configure Yubikey validation service via Django admin Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/installation.rst Sets up a YubiKey validation service named 'default' within the Django admin interface. This is required for YubiKey authentication. ```python from otp_yubikey.models import ValidationService ValidationService.objects.create( name='default', use_ssl=True, param_sl='', param_timeout='' ) ``` -------------------------------- ### Configure Django INSTALLED_APPS Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Adds necessary django-otp and django-two-factor-auth apps to the INSTALLED_APPS setting in Django's settings.py for core and plugin functionalities. ```python INSTALLED_APPS = [ ... 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'django_otp.plugins.otp_email', # <- for email capability. 'otp_yubikey', # <- for yubikey capability. 'two_factor', 'two_factor.plugins.phonenumber', # <- for phone number capability. 'two_factor.plugins.email', # <- for email capability. 'two_factor.plugins.yubikey', # <- for yubikey capability. ] ``` -------------------------------- ### Configure Django MIDDLEWARE Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Adds the OTPMiddleware from django-otp to the MIDDLEWARE setting in Django's settings.py. It should be placed after AuthenticationMiddleware. ```python MIDDLEWARE = ( ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', ... ) ``` -------------------------------- ### Include Two-Factor URLs in Project URLs Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Includes the URL patterns for django-two-factor-auth into the project's main URL configuration (urls.py). ```python from two_factor.urls import urlpatterns as tf_urls urlpatterns = [ path('', include(tf_urls)), ... ] ``` -------------------------------- ### Configure Django LOGIN URLs Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Sets the LOGIN_URL and optionally LOGIN_REDIRECT_URL in Django's settings.py to point to the two-factor authentication login and redirect pages. ```python LOGIN_URL = 'two_factor:login' # this one is optional LOGIN_REDIRECT_URL = 'two_factor:profile' ``` -------------------------------- ### Views Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section covers the various views provided by Django Two-Factor Auth for managing two-factor authentication, including setup, verification, and backup token management. ```APIDOC ## Views ### BackupTokensView **Description**: A view class in `two_factor.views` for managing backup tokens. ### DisableView **Description**: A view class in `two_factor.views` for disabling two-factor authentication for a user. ### LoginView **Description**: A view class in `two_factor.views` that handles the login process, including OTP verification. ### PhoneDeleteView **Description**: A view class in `two_factor.plugins.phonenumber.views` for deleting a phone number as a two-factor device. ### PhoneSetupView **Description**: A view class in `two_factor.plugins.phonenumber.views` for setting up a phone number as a two-factor device. ### ProfileView **Description**: A view class in `two_factor.views` for managing user profile settings related to two-factor authentication. ### SetupCompleteView **Description**: A view class in `two_factor.views` that marks the two-factor setup process as complete. ### SetupView **Description**: A view class in `two_factor.views` that guides the user through the initial setup of two-factor authentication. ``` -------------------------------- ### Handle user_verified Signal Source: https://django-two-factor-auth.readthedocs.io/en/stable/implementing This code demonstrates how to use the `user_verified` signal to trigger actions after a user successfully authenticates with OTP. It includes the user, device, and request, allowing for custom logic, such as sending notifications when a backup token is used. This example sends an email when a backup token is used. ```python from django.contrib.sites.shortcuts import get_current_site from django.dispatch import receiver from two_factor.signals import user_verified @receiver(user_verified) def test_receiver(request, user, device, **kwargs): current_site = get_current_site(request) if device.name == 'backup': message = 'Hi %(username)s,\n\n' 'You\'ve verified yourself using a backup device ' 'on %(site_name)s. If this wasn\'t you, your ' 'account might have been compromised. You need to ' 'change your password at once, check your backup ' 'phone numbers and generate new backup tokens.'\ % {'username': user.get_username(), 'site_name': current_site.name} user.email_user(subject='Backup token used', message=message) ``` -------------------------------- ### Configure YubiKey Validation Service via Shell Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Creates a default YubiKey validation service entry in the Django database using the manage.py shell. This is necessary for YubiKey authentication. ```python $ python manage.py shell >>> from otp_yubikey.models import ValidationService >>> ValidationService.objects.create( ... name='default', use_ssl=True, param_sl='', param_timeout='' ... ) ``` -------------------------------- ### Configure WebAuthn Root Certificates for Two-Factor Authentication Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/configuration.rst This example demonstrates how to configure root certificates for WebAuthn attestation verification in Django Two-Factor Auth. It specifies how to load and format certificates for different attestation formats like PACKED and FIDO_U2F. ```python from webauthn.helpers.structs import AttestationFormat yubico_u2f_ca = """ -----BEGIN CERTIFICATE----- (Yubico's root CA goes here) -----END CERTIFICATE----- """ root_ca_list = [yubico_u2f_ca.encode('ascii')] TWO_FACTOR_WEBAUTHN_PEM_ROOT_CERTS_BYTES_BY_FMT = { AttestationFormat.PACKED: root_ca_list, AttestationFormat.FIDO_U2F: root_ca_list, } ``` -------------------------------- ### Configure Django SECURE_PROXY_SSL_HEADER Source: https://django-two-factor-auth.readthedocs.io/en/stable/installation Sets the SECURE_PROXY_SSL_HEADER setting in Django's settings.py to correctly handle HTTPS traffic when behind a proxy. This is required for WebAuthn on non-localhost domains. ```python SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ``` -------------------------------- ### Configure Twilio URLs for Two-Factor Auth Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/configuration.rst Example of how to include Twilio-specific URLs in your Django project's URL configuration. This is necessary for the Twilio gateway to handle incoming requests related to phone-based two-factor authentication. ```python from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_urls urlpatterns = [ # ... other urlpatterns *tf_twilio_urls, ] ``` -------------------------------- ### Configure Logging for Fake Gateway in Django Source: https://django-two-factor-auth.readthedocs.io/en/stable/configuration Sets up Django's logging configuration to display two-factor authentication tokens in the console using the Fake gateway. This is useful for local development and testing purposes. ```python LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'two_factor': { 'handlers': ['console'], 'level': 'INFO', } } } ``` -------------------------------- ### Check User Verification Status Source: https://django-two-factor-auth.readthedocs.io/en/stable/implementing The `is_verified()` method, added by `OTPMiddleware`, checks if a user has successfully logged in using two-factor authentication. This allows for custom logic based on the user's authentication status. It provides a flexible way to control access to resources based on 2FA. ```python def my_view(request): if request.user.is_verified(): # user logged in using two-factor pass else: # user not logged in using two-factor pass ``` -------------------------------- ### Management Commands Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section covers the management commands provided for interacting with the two-factor authentication system. ```APIDOC ## Management Commands ### two_factor_disable command **Description**: A management command in `two_factor.management.commands.two_factor_disable` to disable two-factor authentication for users. ### two_factor_status command **Description**: A management command in `two_factor.management.commands.two_factor_status` to check the two-factor authentication status of users. ``` -------------------------------- ### Django OTP Integration Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section outlines the integration points with Django OTP, including decorators, middleware, and device models. ```APIDOC ## Django OTP Integration ### otp_required decorator **Description**: A decorator in `django_otp.decorators` to protect views requiring OTP verification. ### OTPMiddleware **Description**: A middleware class in `django_otp.middleware` that assists with OTP processing. ### StaticDevice **Description**: A model class in `django_otp.plugins.otp_static.models` representing a static token device. ### StaticToken **Description**: A model class in `django_otp.plugins.otp_static.models` representing a single static token. ### TOTPDevice **Description**: A model class in `django_otp.plugins.otp_totp.models` representing a Time-based One-Time Password device. ``` -------------------------------- ### Idempotent Session Wizard View Utilities Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Enhances Django's WizardView to handle steps that can be marked as non-idempotent. It manages step visibility, navigation, processing, and final rendering, ensuring data integrity and preventing manipulation. ```python class IdempotentSessionWizardView(_** kwargs_): """WizardView that allows certain steps to be marked non-idempotent, in which case the form is only validated once and the cleaned values stored.""" def get_next_step(_step =None_): """Returns the next step after the given step. If no more steps are available, None will be returned. If the step argument is None, the current step will be determined automatically.""" pass def get_prev_step(_step =None_): """Returns the previous step before the given step. If there are no steps available, None will be returned. If the step argument is None, the current step will be determined automatically.""" pass def is_step_visible(_step_ , _form_class_): """Returns whether the given step should be included in the wizard; it is included if either the form is idempotent or not filled in before.""" pass def post(_* args_, _** kwargs_): """Check if the current step is still available. It might not be if conditions have changed.""" pass def process_step(_form_): """Stores the validated data for form and cleans out validated forms for next steps, as those might be affected by the current step. Note that this behaviour is relied upon by the LoginView to prevent users from bypassing the TokenForm by going steps back and changing credentials.""" pass def render_done(_form_ , _** kwargs_): """This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don’t validate, render_revalidation_failure should get called. If everything is fine call done.""" pass ``` -------------------------------- ### Django OTP Middleware for Request Processing Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference The OTPMiddleware integrates with Django's request lifecycle to enhance user authentication. It populates `request.user.otp_device` with the verified OTP device or None if not verified. It also adds a convenience method `user.is_verified()` to check authentication status. ```python from django.contrib.auth.middleware import AuthenticationMiddleware class OTPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Process request response = self.get_response(request) # Post-processing of the response, or check for exceptions if hasattr(request, 'user') and request.user.is_authenticated: # Populate request.user.otp_device and add user.is_verified() pass return response ``` -------------------------------- ### Utility Functions and Modules Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section lists utility functions and modules used for phone number formatting, signal handling, and other helper functionalities. ```APIDOC ## Utility Functions and Modules ### phonenumber module **Description**: Contains template tags for phone number manipulation, such as `format_phone_number` and `mask_phone_number`. ### signals module **Description**: Contains signals related to two-factor authentication events, such as `user_verified`. ### validate_remember_device_cookie function **Description**: A utility function in `two_factor.views.utils` for validating the 'remember device' cookie. ``` -------------------------------- ### Configure Django Middleware for Two-Factor Authentication Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/configuration.rst This snippet shows how to configure the Django settings to include the necessary middleware for two-factor authentication, specifically for OTP and Twilio gateway. ```python MIDDLEWARE = ( ... # Always include for two-factor auth 'django_otp.middleware.OTPMiddleware', # Include for Twilio gateway 'two_factor.middleware.threadlocals.ThreadLocals', ) ``` -------------------------------- ### Enable ThreadLocals Middleware for Twilio Gateway Source: https://django-two-factor-auth.readthedocs.io/en/stable/configuration Configures Django's middleware settings to include `OTPMiddleware` and `ThreadLocals` middleware. `ThreadLocals` is specifically required for the Twilio gateway to function correctly. ```python MIDDLEWARE = ( ... # Always include for two-factor auth 'django_otp.middleware.OTPMiddleware', # Include for Twilio gateway 'two_factor.middleware.threadlocals.ThreadLocals', ) ``` -------------------------------- ### Django OTP Models for Two-Factor Authentication Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Defines models for different two-factor authentication devices. Includes PhoneDevice for phone number verification, StaticDevice and StaticToken for emergency tokens, and TOTPDevice for Time-based One-Time Password authentication with configurable parameters like key, step, and tolerance. ```python class PhoneDevice(models.Model): # Model with phone number and token seed linked to a user. pass class StaticDevice(models.Model): # A static `Device` simply consists of random tokens shared by the database and the user. # These are frequently used as emergency tokens in case a user’s normal device is lost or unavailable. # They can be consumed in any order; each token will be removed from the database as soon as it is used. # This model has no fields of its own, but serves as a container for `StaticToken` objects. token_set = models.RelatedManager() class StaticToken(models.Model): # A single token belonging to a `StaticDevice`. device = models.ForeignKey(StaticDevice, on_delete=models.CASCADE) token = models.CharField(max_length=16) class TOTPDevice(models.Model): # A generic TOTP `Device`. # The model fields mostly correspond to the arguments to `django_otp.oath.totp()`. # They all have sensible defaults, including the key, which is randomly generated. key = models.CharField(max_length=40) # Hex-encoded secret key step = models.PositiveSmallIntegerField(default=30) # Time step in seconds t0 = models.BigIntegerField(default=0) # Unix time to begin counting steps digits = models.PositiveSmallIntegerField(default=6) # Number of digits in token tolerance = models.PositiveSmallIntegerField(default=1) # Allowed time steps in past/future drift = models.SmallIntegerField(default=0) # Known deviation from our clock last_t = models.BigIntegerField(default=-1) # Time step of the last verified token ``` -------------------------------- ### Utility Classes and Mixins Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section details utility classes and mixins used within Django Two-Factor Auth for managing session state, wizard views, and OTP requirements. ```APIDOC ## Utility Classes and Mixins ### ExtraSessionStorage **Description**: A class in `two_factor.views.utils` for extending session storage capabilities. ### IdempotentSessionWizardView **Description**: A base class in `two_factor.views.utils` for creating wizard views that are idempotent. ### LoginStorage **Description**: A class in `two_factor.views.utils` for managing login-related session data. ### OTPRequiredMixin **Description**: A mixin class in `two_factor.views.mixins` that enforces OTP verification for views. ``` -------------------------------- ### AdminSiteOTPRequired Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference AdminSite class that enforces OTP verification for staff users. ```APIDOC ## AdminSiteOTPRequired ### Description AdminSite enforcing OTP verified staff users. ### Class `two_factor.admin.AdminSiteOTPRequired` ### Parameters - **name** (str) - Optional - The name for the admin site. ``` -------------------------------- ### Gateways Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section details the available gateways for sending one-time passwords, including fake and Twilio implementations. ```APIDOC ## Gateways ### Fake Gateway **Description**: A fake gateway implementation in `two_factor.gateways.fake` for testing purposes. ### Twilio Gateway **Description**: A gateway implementation in `two_factor.gateways.twilio.gateway` for sending OTPs via Twilio. ``` -------------------------------- ### Session Storage Utilities for Django Two-Factor Auth Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Provides custom session storage classes for managing state across multi-step authentication processes. ExtraSessionStorage stores cleaned form data per step, while LoginStorage holds authenticated user information. ```python class ExtraSessionStorage(_* args_, _** kwargs_): """SessionStorage that includes the property validated_step_data for storing cleaned form data per step.""" pass class LoginStorage(_* args_, _** kwargs_): """SessionStorage that includes the property ‘authenticated_user’ for storing backend authenticated users while logging in.""" pass ``` -------------------------------- ### Handle User Verified Signal Source: https://django-two-factor-auth.readthedocs.io/en/stable/_sources/implementing.rst The `user_verified` signal is sent after a user successfully verifies using OTP. This signal includes the user, the device used, and the request. You can use this signal to perform actions, such as warning a user when a backup token is used. This allows for custom actions after successful 2FA verification. ```python from django.contrib.sites.shortcuts import get_current_site from django.dispatch import receiver from two_factor.signals import user_verified @receiver(user_verified) def test_receiver(request, user, device, **kwargs): current_site = get_current_site(request) if device.name == 'backup': message = 'Hi %(username)s,\n\n'\ 'You\'ve verified yourself using a backup device '\ 'on %(site_name)s. If this wasn\'t you, your '\ 'account might have been compromised. You need to '\ 'change your password at once, check your backup '\ 'phone numbers and generate new backup tokens.'\ % {'username': user.get_username(), 'site_name': current_site.name} user.email_user(subject='Backup token used', message=message) ``` -------------------------------- ### Remember Device Cookie Generation and Validation Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Utilities for creating and verifying a secure, signed cookie used to remember a user's device. get_remember_device_cookie generates the cookie, while validate_remember_device_cookie verifies its authenticity and expiry. ```python def get_remember_device_cookie(_user_ , _otp_device_id_): """Compile a signed cookie from user.pk, user.password and otp_device_id, but only return the hashed and signatures and omit the data. The cookie is composed of 3 parts: 1. A timestamp of signing. 2. A hashed value of otp_device_id and the timestamp. 3. A hashed value of user.pk, user.password, otp_device_id and the timestamp.""" pass def validate_remember_device_cookie(_cookie_ , _user_ , _otp_device_id_): """Returns True if the cookie was returned by get_remember_device_cookie using the same user.pk, user.password and otp_device_id. Moreover the cookie must not be expired. Returns False if the otp_device_id does not match. Otherwise raises an exception.""" pass ``` -------------------------------- ### Admin Components Source: https://django-two-factor-auth.readthedocs.io/en/stable/genindex This section details the administrative components provided by Django Two-Factor Auth, such as OTP-required mixins and custom admin sites. ```APIDOC ## Admin Components ### AdminSiteOTPRequired **Description**: A class in `two_factor.admin` that integrates OTP verification into the Django admin site. ### AdminSiteOTPRequiredMixin **Description**: A mixin class in `two_factor.admin` to enforce OTP verification for admin site access. ``` -------------------------------- ### AdminSiteOTPRequiredMixin Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Mixin for enforcing OTP verification for staff users in Django admin views. ```APIDOC ## AdminSiteOTPRequiredMixin ### Description Mixin for enforcing OTP verified staff users. Custom admin views should either be wrapped using `admin_view()` or use `has_permission()` in order to secure those views. ### Class `two_factor.admin.AdminSiteOTPRequiredMixin` ``` -------------------------------- ### Limit Access to Views with OTP Mixin Source: https://django-two-factor-auth.readthedocs.io/en/stable/implementing The `OTPRequiredMixin` is used to limit access to class-based views (CBVs), ensuring that only users with two-factor authentication enabled can access them. This mixin is incorporated into the class definition, providing a reusable way to secure multiple views. It is an alternative to the decorator approach. ```python class ExampleSecretView(OTPRequiredMixin, TemplateView): template_name = 'secret.html' ``` -------------------------------- ### Configure Django URLs for Twilio Gateway Source: https://django-two-factor-auth.readthedocs.io/en/stable/configuration Adds the Twilio gateway's URL patterns to your Django project's `urls.py`. This enables the routing for two-factor authentication requests handled by Twilio. ```python # urls.py from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_urls urlpatterns = [ path('', include(tf_twilio_urls)), ... ] ``` -------------------------------- ### Patch Admin Site for OTP Enforcement Source: https://django-two-factor-auth.readthedocs.io/en/stable/implementing This code snippet demonstrates how to patch the default Django admin site to enforce two-factor authentication. It replaces the default `AdminSite` class with `AdminSiteOTPRequired`, ensuring that users must complete OTP verification to access the admin interface. This is crucial for securing the admin panel. ```python from django.contrib import admin from two_factor.admin import AdminSiteOTPRequired admin.site.__class__ = AdminSiteOTPRequired urlpatterns = [ path('admin/', admin.site.urls), ... ] ``` -------------------------------- ### otp_required Decorator Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Decorator to ensure a user is OTP verified, similar to Django's login_required. ```APIDOC ## otp_required() ### Description Similar to `login_required()`, but requires the user to be verified. By default, this redirects users to `OTP_LOGIN_URL`. ### Decorator `django_otp.decorators.otp_required` ### Parameters - **view** (callable) - Optional - The view function to wrap. - **redirect_field_name** (str) - Optional - The name of the query parameter to store the redirect URL. Defaults to 'next'. - **login_url** (str) - Optional - The URL to redirect to for login if the user is not verified. Defaults to `OTP_LOGIN_URL`. - **if_configured** (bool) - Optional - If `True`, an authenticated user with no confirmed OTP devices will be allowed. Defaults to `False`. ``` -------------------------------- ### Django Signal for User Verification Events Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference The `user_verified` signal is triggered in Django when a user successfully authenticates using an OTP device. It provides context about the verification event, including the sender, the user object, the OTP device used, and the associated HTTP request. ```python from django.dispatch import Signal user_verified = Signal() # Arguments: sender, user, device, request ``` -------------------------------- ### Django Template Tags for Phone Number Formatting Source: https://django-two-factor-auth.readthedocs.io/en/stable/class-reference Provides utility template tags for handling phone numbers within Django templates. `device_action` generates user-friendly text for phone verification actions. `format_phone_number` formats numbers in international notation, and `mask_phone_number` masks the number to show only the first three and last two digits. ```django {% load phonenumber %} {# Example usage of device_action #} {{ device|device_action }} {# Example usage of format_phone_number #} {{ phone_number|format_phone_number }} {# Example usage of mask_phone_number #} {{ phone_number|mask_phone_number }} ``` -------------------------------- ### Limit Access to Views with OTP Decorator Source: https://django-two-factor-auth.readthedocs.io/en/stable/implementing The `otp_required` decorator from `django_otp` restricts access to a view, ensuring that only users who have enabled two-factor authentication can access it. This decorator is applied directly above the view function, providing a simple way to secure specific parts of the website. It leverages the django-otp library for authentication. ```python from django_otp.decorators import otp_required @otp_required def my_view(request): pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.