### Install django-phone-verify package via pip Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Installs the django-phone-verify package with optional SMS backend extras. Install with Twilio support for most users, Nexmo/Vonage for alternative providers, or all extras for comprehensive functionality. ```shell # Install with Twilio support (recommended for most users) pip install django-phone-verify[twilio] # Or install with Nexmo/Vonage support pip install django-phone-verify[nexmo] # Install with all supported backends pip install django-phone-verify[all] # Core only (if you're writing a custom backend) pip install django-phone-verify ``` -------------------------------- ### Set up environment variables for Twilio credentials Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Creates environment variable configuration in .env file for Twilio SMS credentials. Should be added to .gitignore for security and loaded in Django settings.py using python-dotenv. ```shell # .env (for Twilio) TWILIO_ACCOUNT_SID=your_account_sid_here TWILIO_AUTH_TOKEN=your_auth_token_here TWILIO_PHONE_NUMBER=+1234567890 ``` -------------------------------- ### Configure Django INSTALLED_APPS for phone verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Adds phone_verify app to Django project's INSTALLED_APPS list in settings.py. This enables the phone verification functionality and creates necessary database tables. ```python # settings.py INSTALLED_APPS = [ ... 'phone_verify', ... ] ``` -------------------------------- ### Configure Nexmo/Vonage SMS backend for phone verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Sets up Nexmo/Vonage backend configuration in Django settings with API credentials, sender ID, and security settings. Uses environment variables for secure credential management. ```python # settings.py import os PHONE_VERIFICATION = { 'BACKEND': 'phone_verify.backends.nexmo.NexmoBackend', 'OPTIONS': { 'KEY': os.environ.get('NEXMO_API_KEY'), # Your Nexmo API Key 'SECRET': os.environ.get('NEXMO_API_SECRET'), # Your Nexmo API Secret 'FROM': 'MyApp', # Sender ID (alphanumeric or phone number) }, 'TOKEN_LENGTH': 6, 'MIN_TOKEN_LENGTH': 6, # Minimum allowed token length for security 'MAX_FAILED_ATTEMPTS': 5, # Maximum failed verification attempts before locking session 'MESSAGE': 'Welcome to {app}! Please use security code {security_code} to proceed.', 'APP_NAME': 'MyApp', 'SECURITY_CODE_EXPIRATION_TIME': 600, 'VERIFY_SECURITY_CODE_ONLY_ONCE': True, } ``` -------------------------------- ### Install django-phone-verify Package Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Installs the django-phone-verify package with all supported backends or specific ones like Twilio or Nexmo. ```shell pip install django-phone-verify[all] pip install django-phone-verify[twilio] pip install django-phone-verify[nexmo] ``` -------------------------------- ### django-phone-verify Installation Command Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/faq.md Shows the pip installation commands for django-phone-verify, including options for Twilio, Nexmo, or both. ```bash pip install django-phone-verify[twilio] ``` ```bash pip install django-phone-verify[nexmo] ``` ```bash pip install django-phone-verify[all] ``` ```bash pip install django-phone-verify ``` -------------------------------- ### Run database migrations for phone verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Executes Django migration command to create the SMSVerification table for storing phone numbers, session tokens, and security codes required for phone verification functionality. ```shell python manage.py migrate ``` -------------------------------- ### Testing Phone Verification with Django Shell in Python Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md This snippet tests the django-phone-verify setup by sending a security code to a phone number and verifying it using the session token. It requires the phone_verify app to be installed and configured in a Django project. Inputs include a phone number and the received security code; outputs are a session token and verification status. Limitations: Testing requires a real phone number for SMS reception and should use actual received codes for verification. ```Python python manage.py shell >>> from phone_verify.services import send_security_code_and_generate_session_token >>> from phone_verify.services import verify_security_code >>> >>> # Send verification code >>> phone = "+1234567890" # Use your real phone number for testing >>> session_token = send_security_code_and_generate_session_token(phone) >>> print(f"Session token: {session_token}") >>> >>> # Check your phone for the SMS, then verify >>> code = "123456" # Enter the code you received >>> verify_security_code(phone, code, session_token) (, 'SECURITY_CODE_VALID') ``` -------------------------------- ### Configure Twilio SMS backend for phone verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Sets up Twilio backend configuration in Django settings with account credentials, message template, and security settings. Uses environment variables for secure credential management. ```python # settings.py import os PHONE_VERIFICATION = { 'BACKEND': 'phone_verify.backends.twilio.TwilioBackend', 'OPTIONS': { 'SID': os.environ.get('TWILIO_ACCOUNT_SID'), # Your Twilio Account SID 'SECRET': os.environ.get('TWILIO_AUTH_TOKEN'), # Your Twilio Auth Token 'FROM': os.environ.get('TWILIO_PHONE_NUMBER'), # Your Twilio phone number (e.g., '+1234567890') }, 'TOKEN_LENGTH': 6, # Length of security code 'MIN_TOKEN_LENGTH': 6, # Minimum allowed token length for security 'MAX_FAILED_ATTEMPTS': 5, # Maximum failed verification attempts before locking session 'MESSAGE': 'Welcome to {app}! Please use security code {security_code} to proceed.', 'APP_NAME': 'MyApp', # Your app name (used in MESSAGE) 'SECURITY_CODE_EXPIRATION_TIME': 600, # 10 minutes (in seconds) 'VERIFY_SECURITY_CODE_ONLY_ONCE': True, # Code can only be used once } ``` -------------------------------- ### Environment-Based Configuration in Django Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Example of using different settings for development and production environments in Django. ```python # settings.py import os DEBUG = os.getenv("DEBUG", "False") == "True" if DEBUG: # Development: Use sandbox PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.twilio.TwilioSandboxBackend", "OPTIONS": { "SID": "fake", "SECRET": "fake", "FROM": "+15551234567", "SANDBOX_TOKEN": "123456", }, "TOKEN_LENGTH": 6, "MESSAGE": "[DEV] Your code is {security_code}", "APP_NAME": "MyApp Dev", "SECURITY_CODE_EXPIRATION_TIME": 7200, # Longer for testing "VERIFY_SECURITY_CODE_ONLY_ONCE": False, # Allow retries } else: # Production: Use real SMS PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.twilio.TwilioBackend", "OPTIONS": { "SID": os.getenv("TWILIO_SID"), "SECRET": os.getenv("TWILIO_SECRET"), "FROM": os.getenv("TWILIO_FROM_NUMBER"), }, "TOKEN_LENGTH": 6, "MESSAGE": "Your {app} verification code is {security_code}", "APP_NAME": "MyApp", "SECURITY_CODE_EXPIRATION_TIME": 600, # 10 minutes "VERIFY_SECURITY_CODE_ONLY_ONCE": True, } ``` -------------------------------- ### Load environment variables in Django settings Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Configures Django settings.py to load environment variables from .env file using python-dotenv library for secure credential management without hardcoding sensitive values. ```python # settings.py from dotenv import load_dotenv load_dotenv() # Load .env file ``` -------------------------------- ### Installation Commands - Shell Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/index.md Shell commands for installing django-phone-verify with different SMS provider backends. Supports selective installation for specific providers (Twilio, Nexmo/Vonage) or complete installation with all backends. Use appropriate extras depending on your SMS provider choice. ```shell # For Twilio users pip install django-phone-verify[twilio] # For Nexmo/Vonage users pip install django-phone-verify[nexmo] # Install all backends pip install django-phone-verify[all] ``` -------------------------------- ### Configure Django URL routing for phone verification API Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/getting_started.md Includes phone verification URLs in Django project's URL configuration to expose /api/phone/register/ and /api/phone/verify/ endpoints when using Django REST Framework API viewsets. ```python # urls.py from django.urls import path, include urlpatterns = [ ... path('api/phone/', include('phone_verify.urls')), ... ] ``` -------------------------------- ### Quick Phone Verification Example - Python Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/index.md Demonstrates basic usage of django-phone-verify for sending SMS verification codes and validating them. Shows the core workflow of generating a session token, sending the code, and verifying it. The example uses the library's service functions which handle JWT tokens, expiration, and security validation internally. ```python from phone_verify.services import send_security_code_and_generate_session_token from phone_verify.services import verify_security_code # Send verification code via SMS session_token = send_security_code_and_generate_session_token("+1234567890") # User receives SMS: "Your verification code is 847291" # Verify the code verify_security_code("+1234567890", "847291", session_token) # Returns: SECURITY_CODE_VALID ``` -------------------------------- ### Python Logging Configuration for Django Phone Verify Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/architecture.md Provides an example of configuring logging in Django's `settings.py` to capture events from the `phone_verify` logger. It specifies a file handler to write INFO level logs to a designated file. ```python # Enable debug logging LOGGING = { 'version': 1, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/django/phone_verify.log', }, }, 'loggers': { 'phone_verify': { 'handlers': ['file'], 'level': 'INFO', }, }, } ``` -------------------------------- ### Django Views for Phone Verification Workflow Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md Implements Django views to handle the phone verification process. `request_code_view` sends a verification code, and `verify_and_register_view` verifies the code and creates a new user. ```python from django.shortcuts import render, redirect from phone_verify.services import PhoneVerificationService from django.contrib.auth import get_user_model from .forms import PhoneRequestForm, VerificationForm def request_code_view(request): if request.method == 'POST': form = PhoneRequestForm(request.POST) if form.is_valid(): phone = form.cleaned_data['phone_number'] verifier = PhoneVerificationService(phone) verifier.send_verification() return redirect(f'/verify/?phone_number={phone}') else: form = PhoneRequestForm() return render(request, 'request_code.html', {'form': form}) def verify_and_register_view(request): if request.method == 'POST': form = VerificationForm(request.POST) if form.is_valid(): phone = form.cleaned_data['phone_number'] code = form.cleaned_data['security_code'] verifier = PhoneVerificationService(phone) if verifier.verify(code): get_user_model().objects.create_user( username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'], ) return redirect('login') else: phone = request.GET.get('phone_number', '') form = VerificationForm(initial={'phone_number': phone}) return render(request, 'verify_and_register.html', {'form': form}) ``` -------------------------------- ### Install Django Phone Verify SMS Providers (Shell) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/troubleshooting.md Installs the necessary provider libraries for django-phone-verify, such as Twilio or Nexmo. The core package is lightweight and requires these extras for SMS functionality. ```shell pip install django-phone-verify[twilio] # For Nexmo pip install django-phone-verify[nexmo] # For both pip install django-phone-verify[all] ``` -------------------------------- ### Django REST Framework Throttling Setup Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Configures DRF throttling classes for phone verification endpoints. Separates throttling policies for registration (3/hour) and verification (10/hour) with custom throttle classes inheriting from AnonRateThrottle. ```python from rest_framework.throttling import AnonRateThrottle, UserRateThrottle class PhoneRegisterThrottle(AnonRateThrottle): rate = '3/hour' class PhoneVerifyThrottle(AnonRateThrottle): rate = '10/hour' class CustomVerificationViewSet(VerificationViewSet): throttle_classes = [PhoneRegisterThrottle] def get_throttles(self): if self.action == 'verify': return [PhoneVerifyThrottle()] return super().get_throttles() ``` -------------------------------- ### Django Template for Verifying Code and Registration Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md An HTML template for the `verify_and_register_view`. It displays a form for users to enter the received security code along with their registration details. ```html
{% csrf_token %} {{ form.as_p }}
``` -------------------------------- ### Django: Service Function for User Account Creation Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md A utility function `create_user_account` that takes user credentials (username, email, password) and optionally other fields, then creates a new user instance using Django's `get_user_model()`. ```python from django.contrib.auth import get_user_model def create_user_account(username, email, password, **extra): return get_user_model().objects.create_user( username=username, email=email, password=password, **extra, ) ``` -------------------------------- ### Implement Custom SMS Backend Class in Python Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/customization.md Creates a production-ready SMS backend by extending the BaseBackend class. Implements SMS sending via Nexmo API, custom message generation with runtime context support, and bulk messaging capabilities. Requires the nexmo client library and valid API credentials for operation. ```python import nexmo from phone_verify.backends.base import BaseBackend class NexmoBackend(BaseBackend): def __init__(self, **options): super().__init__(**options) options = {key.lower(): value for key, value in options.items()} self._key = options.get("key") self._secret = options.get("secret") self._from = options.get("from") self.client = nexmo.Client(key=self._key, secret=self._secret) def send_sms(self, number, message): self.client.send_message({ 'from': self._from, 'to': number, 'text': message, }) def generate_message(self, security_code, context=None): """You can optionally override the message formatting by defining a `generate_message()` method in your backend. This method receives the `security_code` and an optional `context` dictionary passed at runtime, giving you more flexibility than using a static `MESSAGE` template.""" username = context.get("username", "User") if context else "User" return f"Hi {username}, your OTP is {security_code}." def send_bulk_sms(self, numbers, message): for number in numbers: self.send_sms(number, message) ``` -------------------------------- ### Implement Sandbox SMS Backend in Python Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/customization.md Implements a sandbox backend for testing phone verification flows without sending real SMS messages. Overrides security code generation to return a constant token and validates any input as successful. Ideal for development and automated testing environments. ```python import nexmo from phone_verify.backends.base import BaseBackend from phone_verify.models import SMSVerification class NexmoSandboxBackend(BaseBackend): def __init__(self, **options): super().__init__(**options) options = {key.lower(): value for key, value in options.items()} self._key = options.get("key") self._secret = options.get("secret") self._from = options.get("from") self._token = options.get("sandbox_token") self.client = nexmo.Client(key=self._key, secret=self._secret) def send_sms(self, number, message): self.client.send_message({ 'from': self._from, 'to': number, 'text': message, }) def generate_message(self, security_code, context=None): return f"[SANDBOX] Your code is {security_code}" def send_bulk_sms(self, numbers, message): for number in numbers: self.send_sms(number, message) def generate_security_code(self): return self._token def validate_security_code(self, security_code, phone_number, session_token): return SMSVerification.objects.none(), self.SECURITY_CODE_VALID ``` -------------------------------- ### Django Settings for Phone Verification with Fallback Backend (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Configures the phone verification system in Django's settings.py, specifying a custom fallback backend and providing distinct options for the primary (Twilio) and fallback (Nexmo) providers. This setup allows for high availability by defining alternative SMS sending services. ```python # settings.py PHONE_VERIFICATION = { "BACKEND": "myapp.backends.FallbackBackend", "OPTIONS": { "primary": { "SID": "...", "SECRET": "...", "FROM": "+15551234567", }, "fallback": { "KEY": "...", "SECRET": "...", "FROM": "MyApp", }, }, ... } ``` -------------------------------- ### Django Template for Requesting Verification Code Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md An HTML template for the `request_code_view`. It renders a form that allows users to submit their phone number to initiate the verification process. ```html
{% csrf_token %} {{ form.as_p }}
``` -------------------------------- ### BaseBackend - Custom Message Generation Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/api_reference.md Example implementation of custom message generation for SMS verification. Extends the abstract BaseBackend to customize OTP message formatting with user context. Override generate_message() method for personalized messages. ```python def generate_message(self, security_code, context=None): username = context.get("username", "User") if context else "User" return f"Hi {username}, your OTP is {security_code}." ``` -------------------------------- ### Configure Django Settings for SMS Backend in Python Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/customization.md Configures Django settings for phone verification using custom SMS backends. Defines backend class path, API credentials, message templates, token length, and security parameters. This settings dictionary controls how verification codes are generated, formatted, and validated across the application. ```python PHONE_VERIFICATION = { 'BACKEND': 'nexmo.NexmoBackend', 'OPTIONS': { 'KEY': 'Fake Key', 'SECRET': 'Fake Secret', 'FROM': '+1234567890', 'SANDBOX_TOKEN': '123456', }, 'TOKEN_LENGTH': 6, 'MESSAGE': 'Welcome to {app}! Please use security code {security_code} to proceed.', 'APP_NAME': 'Phone Verify', 'SECURITY_CODE_EXPIRATION_TIME': 3600, 'VERIFY_SECURITY_CODE_ONLY_ONCE': True, } ``` ```python PHONE_VERIFICATION = { 'BACKEND': 'nexmo.NexmoSandboxBackend', 'OPTIONS': { 'KEY': 'Fake Key', 'SECRET': 'Fake Secret', 'FROM': '+1234567890', 'SANDBOX_TOKEN': '123456', }, 'TOKEN_LENGTH': 6, 'MESSAGE': 'Welcome to {app}! Please use security code {security_code} to proceed.', 'APP_NAME': 'Phone Verify', 'SECURITY_CODE_EXPIRATION_TIME': 3600, 'VERIFY_SECURITY_CODE_ONLY_ONCE': True, } ``` -------------------------------- ### Send Verification Code Asynchronously with Celery (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/faq.md Demonstrates how to send verification codes asynchronously using Celery to improve API response times. This involves creating a Celery task that utilizes the PhoneVerificationService. It requires Celery to be installed and configured. ```python # tasks.py from celery import shared_task from phone_verify.services import PhoneVerificationService @shared_task def send_verification_code_async(phone_number): service = PhoneVerificationService(phone_number) return service.send_verification() ``` -------------------------------- ### DRF: Custom Serializers for User Data and Phone Verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md Defines custom DRF serializers. `YourUserSerializer` handles username, email, and password. `YourCustomSerializer` combines `YourUserSerializer` with `SMSVerificationSerializer` for a comprehensive input. ```python from rest_framework import serializers from phone_verify.serializers import SMSVerificationSerializer class YourUserSerializer(serializers.Serializer): username = serializers.CharField() email = serializers.EmailField() password = serializers.CharField() class YourCustomSerializer(YourUserSerializer, SMSVerificationSerializer): pass ``` -------------------------------- ### Mock SMS Sending with unittest.mock Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/troubleshooting.md Provides an example of mocking the `send_sms` method of the `TwilioBackend` using `unittest.mock.patch` for testing. This allows verification that the SMS sending function was called correctly without executing the actual SMS sending logic. ```python from unittest.mock import patch @patch('phone_verify.backends.twilio.TwilioBackend.send_sms') def test_verification(mock_send_sms): # Your test code here mock_send_sms.assert_called_once() ``` -------------------------------- ### Django: Registering DRF ViewSet in URLs Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md Configures URL routing for the custom DRF ViewSet using `DefaultRouter`. It registers `YourCustomViewSet` under the '/phone' endpoint, setting the basename to 'phone'. ```python from rest_framework.routers import DefaultRouter from yourapp.api import YourCustomViewSet router = DefaultRouter(trailing_slash=False) router.register('phone', YourCustomViewSet, basename='phone') urlpatterns = router.urls ``` -------------------------------- ### DRF: Custom ViewSet for Phone Verification and Registration Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md Creates a custom DRF ViewSet inheriting from `VerificationViewSet` to handle phone verification and user registration. It uses `SMSVerificationSerializer` for phone verification and a custom `YourUserSerializer` for user details, integrating with a user creation service. ```python from rest_framework.decorators import action from rest_framework.permissions import AllowAny from rest_framework.response import Response from phone_verify.api import VerificationViewSet from phone_verify import serializers as phone_serializers from . import services, serializers class YourCustomViewSet(VerificationViewSet): @action( detail=False, methods=['POST'], permission_classes=[AllowAny], serializer_class=serializers.YourCustomSerializer, ) def verify_and_register(self, request): phone_serializer = phone_serializers.SMSVerificationSerializer(data=request.data) phone_serializer.is_valid(raise_exception=True) user_serializer = serializers.YourUserSerializer(data=request.data) user_serializer.is_valid(raise_exception=True) user = services.create_user_account(**user_serializer.validated_data) return Response(user_serializer.data) ``` -------------------------------- ### Use Sandbox Backend for Testing Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Configures a sandbox backend for testing phone verification, avoiding production risks. ```Python # Development settings PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.twilio.TwilioSandboxBackend", "OPTIONS": { "SANDBOX_TOKEN": "123456", ... }, ... } ``` -------------------------------- ### Configure Nexmo (Vonage) Backend Settings Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Sets up the PHONE_VERIFICATION settings for using Nexmo (Vonage) as the SMS backend, including necessary options. ```python PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.nexmo.NexmoBackend", "OPTIONS": { ``` -------------------------------- ### Validate International Phone Numbers with phonenumbers Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md A function to parse phone numbers and check if they belong to allowed countries, specifically US and Canada in this example. It uses the `phonenumbers` library. ```python import phonenumbers def is_allowed_country(phone_number): """Only allow specific countries""" try: parsed = phonenumbers.parse(phone_number, None) country = phonenumbers.region_code_for_number(parsed) # Allow only US and Canada return country in ['US', 'CA'] except: return False class CustomVerificationViewSet(VerificationViewSet): @action(detail=False, methods=['POST']) def register(self, request): phone = request.data.get('phone_number') if not is_allowed_country(phone): return Response( {"error": "Phone number country not supported"}, status=400 ) return super().register(request) ``` -------------------------------- ### Basic Configuration Structure Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Main configuration dictionary that defines all django-phone-verify settings in Django settings.py. Contains backend selection, security parameters, and message configuration. ```python PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.twilio.TwilioBackend", "OPTIONS": {...}, "TOKEN_LENGTH": 6, "MESSAGE": "Your code is {security_code}", "APP_NAME": "MyApp", "SECURITY_CODE_EXPIRATION_TIME": 3600, "VERIFY_SECURITY_CODE_ONLY_ONCE": False, } ``` -------------------------------- ### Delete User Phone Data for GDPR Compliance Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Example code for deleting all SMS verification data associated with a specific phone number, fulfilling GDPR data deletion requirements. ```python # Example: GDPR data deletion from phone_verify.models import SMSVerification def delete_user_phone_data(phone_number): """Delete all verification data for a phone number""" SMSVerification.objects.filter(phone_number=phone_number).delete() ``` -------------------------------- ### Django Settings Configuration (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/faq.md Demonstrates how to configure Twilio credentials within Django settings using environment variables. This helps to avoid hardcoding sensitive credentials. ```python import os PHONE_VERIFICATION = { 'OPTIONS': { 'SID': os.environ.get('TWILIO_ACCOUNT_SID'), 'SECRET': os.environ.get('TWILIO_AUTH_TOKEN'), 'FROM': os.environ.get('TWILIO_PHONE_NUMBER'), }, # ... other settings } ``` -------------------------------- ### Django Forms for Phone Verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/integration.md Defines Django forms for requesting a verification code and for submitting the verification code along with user registration details. The `VerificationForm` includes a hidden field for the phone number. ```python from django import forms class PhoneRequestForm(forms.Form): phone_number = forms.CharField() class VerificationForm(forms.Form): phone_number = forms.CharField(widget=forms.HiddenInput) security_code = forms.CharField() username = forms.CharField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) ``` -------------------------------- ### Configure INSTALLED_APPS for django-phone-verify Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Adds 'phone_verify' to the INSTALLED_APPS setting in Django projects to enable the app. ```python INSTALLED_APPS = [ ... "phone_verify", ... ] ``` -------------------------------- ### Secure Credential Storage with Environment Variables Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Demonstrates secure credential management for phone verification services. Uses environment variables instead of hard-coded credentials to prevent credential exposure in source code and supports integration with secrets management systems. ```python import os # GOOD - Credentials from environment PHONE_VERIFICATION = { "OPTIONS": { "SID": os.getenv("TWILIO_ACCOUNT_SID"), "SECRET": os.getenv("TWILIO_AUTH_TOKEN"), }, ... } ``` ```python # BAD - Credentials in source code PHONE_VERIFICATION = { "OPTIONS": { "SID": "AC1234567890abcdef", "SECRET": "my_secret_token", }, ... } ``` -------------------------------- ### Complete Production Phone Verification Configuration (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md A comprehensive production configuration for Django's phone verification, utilizing environment variables for security credentials. It specifies the Twilio backend, sets security code parameters like length and expiration, and defines message templates. Requires `python-dotenv` for loading environment variables. ```python # settings.py import os from dotenv import load_dotenv load_dotenv() # Phone Verification Configuration PHONE_VERIFICATION = { # Backend "BACKEND": "phone_verify.backends.twilio.TwilioBackend", # Provider Credentials (from environment) "OPTIONS": { "SID": os.getenv("TWILIO_ACCOUNT_SID"), "SECRET": os.getenv("TWILIO_AUTH_TOKEN"), "FROM": os.getenv("TWILIO_PHONE_NUMBER"), }, # Security Code Settings "TOKEN_LENGTH": 6, "SECURITY_CODE_EXPIRATION_TIME": 600, # 10 minutes "VERIFY_SECURITY_CODE_ONLY_ONCE": True, # Message Settings "APP_NAME": "Acme Corporation", "MESSAGE": "Your Acme verification code is {security_code}. Valid for 10 minutes.", } # Installed Apps INSTALLED_APPS = [ ... 'phone_verify', 'rest_framework', 'phonenumber_field', ... ] ``` -------------------------------- ### PhoneVerificationService Interface (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/architecture.md Outlines the main service class for handling phone verification. It includes methods for sending verification codes and verifying the submitted security code against a session token. ```python class PhoneVerificationService: def send_verification(self, context=None) # Generates code, sends SMS, returns session token def verify(self, security_code, session_token) # Validates code and token, returns success/failure ``` -------------------------------- ### Configure Twilio Backend Settings Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Sets up the PHONE_VERIFICATION settings for using Twilio as the SMS backend, including credentials, phone number, and token options. ```python PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.twilio.TwilioBackend", "OPTIONS": { "SID": "your-twilio-account-sid", "SECRET": "your-twilio-auth-token", "FROM": "+1234567890", # Your Twilio phone number "SANDBOX_TOKEN": "123456", # Optional: for testing without sending real SMS }, "TOKEN_LENGTH": 6, "MESSAGE": "Welcome to {app}! Please use security code {security_code} to proceed.", "APP_NAME": "Phone Verify", "SECURITY_CODE_EXPIRATION_TIME": 3600, # in seconds "VERIFY_SECURITY_CODE_ONLY_ONCE": False, } ``` -------------------------------- ### Include django-phone-verify URLs Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Integrates the phone verification API URLs into the project's main urls.py file. ```python from django.urls import path, include urlpatterns = [ ... path("api/phone/", include("phone_verify.urls")), ... ] ``` -------------------------------- ### Backend Configuration Options Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Backend-specific configuration for different SMS providers. Includes Twilio, Nexmo, and custom backend options with required credentials and optional sandbox token. ```python # Twilio Backend Configuration "OPTIONS": { "SID": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", # Twilio Account SID "SECRET": "your_auth_token", # Twilio Auth Token "FROM": "+15551234567", # Your Twilio phone number (E.164) "SANDBOX_TOKEN": "123456", # Optional: fixed token for sandbox } ``` ```python # Nexmo Backend Configuration "OPTIONS": { "KEY": "your_api_key", # Nexmo API Key "SECRET": "your_api_secret", # Nexmo API Secret "FROM": "YourApp", # Sender ID (alphanumeric) or phone number "SANDBOX_TOKEN": "123456", # Optional: fixed token for sandbox } ``` ```python # Custom Backend Configuration "BACKEND": "myapp.backends.CustomSMSBackend" "OPTIONS": { # Define whatever keys your custom backend needs } ``` -------------------------------- ### Create a Sandbox Backend for Testing (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/faq.md Implements a sandbox backend that returns a fixed security code, useful for testing without sending real SMS messages. This class inherits from TwilioBackend and overrides generate_security_code(). It allows specifying a SANDBOX_TOKEN in options. ```python class TwilioSandboxBackend(TwilioBackend): def generate_security_code(self): return self.options.get('SANDBOX_TOKEN', '123456') ``` -------------------------------- ### Nexmo Sandbox Backend Configuration in Django Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Configures the Nexmo sandbox backend for development and testing without sending real SMS. ```python PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.nexmo.NexmoSandboxBackend", "OPTIONS": { "KEY": "fake_key", "SECRET": "fake_secret", "FROM": "TestApp", "SANDBOX_TOKEN": "999999", # All codes will be "999999" }, ... } ``` -------------------------------- ### Base Backend Interface for SMS Providers (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/architecture.md Defines an abstract interface for SMS backend providers. It specifies methods for sending SMS (single and bulk), generating security codes and JWT tokens, and validating security codes. ```python class BaseBackend: def send_sms(number, message) # Send single SMS def send_bulk_sms(numbers, message) # Send bulk SMS def generate_security_code() # Generate random code def generate_session_token(phone_number) # Generate JWT token def validate_security_code(...) # Validate code ``` -------------------------------- ### PhoneVerificationService - Send SMS Verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/api_reference.md Demonstrates how to instantiate the PhoneVerificationService and send verification SMS with custom context. Uses the main service class to send security codes to phone numbers. Requires django-phone-verify package and configured SMS backend. ```python from phone_verify.services import PhoneVerificationService service = PhoneVerificationService(phone_number="+1234567890") service.send_verification( number="+1234567890", security_code="123456", context={"username": "Alice"} ) ``` -------------------------------- ### Django Settings for Phone Verification Configuration Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/architecture.md Illustrates the `PHONE_VERIFICATION` dictionary in Django's `settings.py` file. This configuration specifies the backend to use for SMS verification, token length, message format, application name, and security code expiration time. ```python PHONE_VERIFICATION = { 'BACKEND': 'phone_verify.backends.twilio.TwilioBackend', 'OPTIONS': { ... }, 'TOKEN_LENGTH': 6, 'MESSAGE': 'Code: {security_code}', 'APP_NAME': 'MyApp', 'SECURITY_CODE_EXPIRATION_TIME': 600, 'VERIFY_SECURITY_CODE_ONLY_ONCE': True, } ``` -------------------------------- ### Rate Limiting Implementation with django-ratelimit Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Implements rate limiting for phone verification endpoints using django-ratelimit package. Limits code requests to 3 per hour and verification attempts to 10 per hour per IP address to prevent brute-force attacks and SMS abuse. ```python from django_ratelimit.decorators import ratelimit from rest_framework.decorators import action from phone_verify.api import VerificationViewSet class CustomVerificationViewSet(VerificationViewSet): @ratelimit(key='ip', rate='3/h', method='POST') @action(detail=False, methods=['POST']) def register(self, request): # Limit to 3 code requests per hour per IP return super().register(request) @ratelimit(key='ip', rate='10/h', method='POST') @action(detail=False, methods=['POST']) def verify(self, request): # Limit to 10 verification attempts per hour per IP return super().verify(request) ``` -------------------------------- ### Custom Fallback Backend for Phone Verification (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Defines a custom backend that uses Twilio as the primary SMS provider and Nexmo as a fallback. It handles potential exceptions from the primary provider and switches to the fallback if an error occurs. This backend requires configuration for both primary and fallback providers. ```python from phone_verify.backends.base import BaseBackend from phone_verify.backends.twilio import TwilioBackend from phone_verify.backends.nexmo import NexmoBackend class FallbackBackend(BaseBackend): def __init__(self, **options): super().__init__(**options) self.primary = TwilioBackend(**options.get("primary", {})) self.fallback = NexmoBackend(**options.get("fallback", {})) def send_sms(self, number, message): try: self.primary.send_sms(number, message) except Exception as e: logger.warning(f"Primary backend failed: {e}, using fallback") self.fallback.send_sms(number, message) def send_bulk_sms(self, numbers, message): # Similar logic pass ``` -------------------------------- ### Send and verify security code in Python Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst This Python code demonstrates how to send a security code via SMS and verify it using the django-phone-verify package. It uses the send_security_code_and_generate_session_token and verify_security_code functions. ```python from phone_verify.services import send_security_code_and_generate_session_token from phone_verify.services import verify_security_code # Send verification code via SMS session_token = send_security_code_and_generate_session_token( phone_number="+1234567890" ) # User receives SMS: "Welcome to Phone Verify! Please use security code 847291 to proceed." # Verify the code user entered try: verify_security_code( phone_number="+1234567890", security_code="847291", session_token=session_token ) print("✓ Phone number verified successfully!") except Exception as e: print(f"✗ Verification failed: {e}") ``` -------------------------------- ### Security Configuration Settings for Phone Verification Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Configures security-critical settings for phone verification including token length (6 digits), expiration time (5-10 minutes), and one-time code enforcement. Recommendations based on threat model and security requirements. ```python PHONE_VERIFICATION = { "TOKEN_LENGTH": 6, # Recommended minimum (1 million combinations) "SECURITY_CODE_EXPIRATION_TIME": 300, # 5 minutes for security-sensitive operations "VERIFY_SECURITY_CODE_ONLY_ONCE": True, # Prevent code reuse ... } ``` ```python PHONE_VERIFICATION = { # Standard registration flows "SECURITY_CODE_EXPIRATION_TIME": 600, # 10 minutes ... } ``` -------------------------------- ### Phone Number-Based Rate Limiting with Cache Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Implements phone-specific rate limiting using Django cache backend. Tracks verification attempts per phone number and blocks requests after 3 failed attempts within 1 hour window. ```python from django.core.cache import cache from rest_framework.exceptions import Throttled class CustomVerificationViewSet(VerificationViewSet): @action(detail=False, methods=['POST']) def register(self, request): phone_number = request.data.get('phone_number') # Check rate limit key = f"phone_verify:{phone_number}:register" attempts = cache.get(key, 0) if attempts >= 3: raise Throttled(detail="Too many requests. Try again later.") # Increment counter cache.set(key, attempts + 1, timeout=3600) # 1 hour return super().register(request) ``` -------------------------------- ### Secure Verification Message Content Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/security.md Defines a secure message template for phone verification, including branding and security warnings. ```Python PHONE_VERIFICATION = { "MESSAGE": "Your Acme Corp verification code is {security_code}. " "Never share this code with anyone, including Acme staff.", ... } ``` -------------------------------- ### Configure Nexmo (Vonage) SMS Backend Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/api_reference.md This Python code sets up the Nexmo (now Vonage) backend for sending verification SMS. It requires Nexmo API Key, API Secret, and a Sender ID or phone number. This configuration is part of the Django settings. ```python PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.nexmo.NexmoBackend", "OPTIONS": { "KEY": "your_api_key", "SECRET": "your_api_secret", "FROM": "YourApp", }, ... } ``` -------------------------------- ### Verify security code via curl Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst This curl command sends a POST request to verify the security code entered by the user. It requires the phone number, security code, and session token. ```bash curl -X POST http://localhost:8000/api/phone/verify/ \ -H "Content-Type: application/json" \ -d '{ "phone_number": "+1234567890", "security_code": "123456", "session_token": "eyJ0eXAiOiJKV1QiLCJhbGc..." }' ``` -------------------------------- ### Message Template Configuration Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md SMS message templates with placeholder support for security codes, app name, and custom context. Supports various message formats for different use cases. ```python # Message Template Examples "MESSAGE": "Your verification code is {security_code}" # With app name "MESSAGE": "Welcome to {app}! Your code is {security_code}" # iOS-friendly (for auto-parsing) "MESSAGE": "Your {app} verification code is {security_code}" # Custom context (if you pass context={'username': 'Alice'}) "MESSAGE": "Hi {username}, your {app} code is {security_code}" ``` -------------------------------- ### POST /api/phone/register/ Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Sends a verification code to the provided phone number via SMS and generates a session token for verification. This endpoint initiates the phone verification process. ```APIDOC ## POST /api/phone/register/ ### Description Sends a verification code to the provided phone number via SMS and generates a session token for verification. ### Method POST ### Endpoint /api/phone/register/ ### Parameters #### Request Body - **phone_number** (string) - Required - The phone number to verify in E.164 format (e.g., +1234567890) ### Request Example { "phone_number": "+1234567890" } ### Response #### Success Response (200) - **session_token** (string) - JWT token used for verification - **phone_number** (string) - The phone number that was sent the verification code #### Response Example { "session_token": "eyJ0eXAiOiJKV1QiLCJhbGci...", "phone_number": "+1234567890" } ``` -------------------------------- ### POST /api/phone/verify/ Source: https://github.com/curiouslearner/django-phone-verify/blob/master/README.rst Verifies the security code entered by the user against the phone number and session token. This endpoint completes the phone verification process. ```APIDOC ## POST /api/phone/verify/ ### Description Verifies the security code entered by the user against the phone number and session token. ### Method POST ### Endpoint /api/phone/verify/ ### Parameters #### Request Body - **phone_number** (string) - Required - The phone number being verified - **security_code** (string) - Required - The security code sent to the user - **session_token** (string) - Required - The JWT token received from registration ### Request Example { "phone_number": "+1234567890", "security_code": "123456", "session_token": "eyJ0eXAiOiJKV1QiLCJhbGc..." } ### Response #### Success Response (200) - **message** (string) - Success message - **phone_number** (string) - The verified phone number #### Response Example { "message": "Security code is valid", "phone_number": "+1234567890" } ``` -------------------------------- ### Security Parameters Configuration Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Security-related settings including token length, expiration time, and verification behavior. Controls security code generation and validation parameters. ```python # Token Length Configuration "TOKEN_LENGTH": 6 # Generates codes like "123456" "TOKEN_LENGTH": 4 # Generates codes like "5738" ``` ```python # Security Code Expiration Time "SECURITY_CODE_EXPIRATION_TIME": 300 # 5 minutes "SECURITY_CODE_EXPIRATION_TIME": 600 # 10 minutes "SECURITY_CODE_EXPIRATION_TIME": 1800 # 30 minutes "SECURITY_CODE_EXPIRATION_TIME": 3600 # 1 hour ``` ```python # App Name Configuration "APP_NAME": "MyApp" "APP_NAME": "Acme Corp" ``` -------------------------------- ### Configure Security Code Verification in Django Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Sets whether a security code can be verified multiple times or only once. Recommended for security-sensitive operations. ```python "VERIFY_SECURITY_CODE_ONLY_ONCE": True # Code can only be used once (recommended) "VERIFY_SECURITY_CODE_ONLY_ONCE": False # Code can be reused within expiration window ``` -------------------------------- ### Configure Django Phone Verification Settings (Python) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/troubleshooting.md Defines the core settings for django-phone-verify in Django's settings.py. This includes specifying the backend, provider credentials, token length, message format, and expiration times. ```python PHONE_VERIFICATION = { "BACKEND": "phone_verify.backends.twilio.TwilioBackend", "OPTIONS": { "SID": "your-sid", "SECRET": "your-secret", "FROM": "+15551234567", }, "TOKEN_LENGTH": 6, "MESSAGE": "Your code is {security_code}", "APP_NAME": "MyApp", "SECURITY_CODE_EXPIRATION_TIME": 3600, "VERIFY_SECURITY_CODE_ONLY_ONCE": False, } ``` -------------------------------- ### Send Bulk Verification SMS using Twilio Backend Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/faq.md Demonstrates how to send verification SMS messages to multiple phone numbers concurrently using the Twilio backend. It requires the phone_verify library and Twilio settings configured in Django. ```python from phone_verify.backends.twilio import TwilioBackend backend = TwilioBackend(**settings.PHONE_VERIFICATION['OPTIONS']) phone_numbers = ['+1234567890', '+0987654321'] message = "Your verification code is 123456" backend.send_bulk_sms(phone_numbers, message) ``` -------------------------------- ### Using Environment Variables in Django Settings Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/configuration.md Stores sensitive credentials in environment variables for security. ```python # settings.py import os PHONE_VERIFICATION = { "BACKEND": os.getenv( "PHONE_VERIFY_BACKEND", "phone_verify.backends.twilio.TwilioBackend" ), "OPTIONS": { "SID": os.getenv("TWILIO_SID"), "SECRET": os.getenv("TWILIO_SECRET"), "FROM": os.getenv("TWILIO_FROM_NUMBER"), }, "TOKEN_LENGTH": int(os.getenv("PHONE_VERIFY_TOKEN_LENGTH", "6")), "MESSAGE": os.getenv( "PHONE_VERIFY_MESSAGE", "Your {app} code is {security_code}" ), "APP_NAME": os.getenv("PHONE_VERIFY_APP_NAME", "MyApp"), "SECURITY_CODE_EXPIRATION_TIME": int( os.getenv("PHONE_VERIFY_EXPIRATION", "600") ), "VERIFY_SECURITY_CODE_ONLY_ONCE": os.getenv( "PHONE_VERIFY_ONCE", "True" ) == "True", } ``` ```shell # .env file TWILIO_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx TWILIO_SECRET=your_auth_token TWILIO_FROM_NUMBER=+15551234567 PHONE_VERIFY_TOKEN_LENGTH=6 PHONE_VERIFY_EXPIRATION=600 PHONE_VERIFY_ONCE=True ``` -------------------------------- ### Enable Debug Logging for django-phone-verify (Python/Django) Source: https://github.com/curiouslearner/django-phone-verify/blob/master/docs/troubleshooting.md This snippet shows how to configure Django's logging to enable debug-level logging for the 'phone_verify' app. This is useful for troubleshooting. It requires the `LOGGING` dictionary to be present in your Django settings. The output is the logging configuration. ```python LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'phone_verify': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } ```