Skip to main content

Advanced authentication with OTP and phone number verification

Project description

Moses

Moses is the Django app that provides OTP authentication and phone number email verification by 6-digit verification codes.

Quick start

  1. Add "moses" to your INSTALLED_APPS setting like this::
    INSTALLED_APPS = [
        ...
        'moses',
        'django.contrib.admin',
        ...
        'social_django',
    ]
  1. Set moses's CustomUser model as AUTH_USER_MODEL::
    AUTH_USER_MODEL = 'moses.CustomUser'
  1. Allow OTP header in django-cors-headers config::
    CORS_ALLOW_HEADERS = (
        *default_headers,
        "otp",
   )
  1. Add MFAModelBackend as Authentication backend to process OTP on authentication::
    AUTHENTICATION_BACKENDS = [
        'social_core.backends.google.GoogleOAuth2',
        'moses.authentication.MFAModelBackend',
        ...
    ]
  1. Add JWTAuthentication to REST_FRAMEWORK's DEFAULT_AUTHENTICATION_CLASSES::
    REST_FRAMEWORK = {
        ...
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'moses.authentication.JWTAuthentication',
        ]
    }
  1. Specify Moses's serializers for Djoser::
    MOSES = {
        "DEFAULT_LANGUAGE": 'en',
        "SEND_SMS_HANDLER": "project.common.sms.send",
        "SENDER_EMAIL": "noreply@example.com",
        "PHONE_NUMBER_VALIDATOR": "project.common.sms.validate_phone_number",
        "DOMAIN": DOMAIN,
        "URL_PREFIX": "http://localhost:8000", # without trailing slash
        "IP_HEADER": "HTTP_CF_CONNECTING_IP" if DEBUG else None,
        "LANGUAGE_CHOICES": (
            ('en', _("English")),
        ),
    }
  1. Add to your root urls.py::
    from moses.admin import OTPAdminAuthenticationForm
    from moses import urls as moses_urls

    admin.site.site_header = _('Admin Panel')
    admin.site.index_title = 'Welcome'
    admin.site.login_form = OTPAdminAuthenticationForm
    urlpatterns = [
        ...
        path('moses/', include(moses_urls, namespace='moses')),
    ]
  1. Run python manage.py migrate to create the accounts models.

  2. Add middleware:

MIDDLEWARE = [
    ...
    'social_django.middleware.SocialAuthExceptionMiddleware',
]
  1. Add context processors:
TEMPLATES[0]['OPTIONS']['context_processors'] += [
    'social_django.context_processors.backends',
    'social_django.context_processors.login_redirect',
]

Telegram Login Widget Authentication

Moses supports authentication via the Telegram Login Widget.

Settings

Add TELEGRAM_BOT_TOKEN to your MOSES configuration:

MOSES = {
    ...
    "TELEGRAM_BOT_TOKEN": "your-bot-token",
}

Endpoints

Step 1: POST /moses/token/telegram/

Send the Telegram Login Widget callback data:

{
    "id": 123456789,
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "photo_url": "https://t.me/i/userpic/...",
    "auth_date": 1234567890,
    "hash": "abc123...",
    "domain": "example.com"
}

Response if user exists:

{"status": "authenticated", "refresh": "...", "access": "..."}

Response if new user:

{"status": "phone_required", "telegram_auth_token": "...", "telegram_id": 123456789, "first_name": "John", ...}

Step 2: POST /moses/token/telegram/complete/ (new users only)

{
    "telegram_auth_token": "temp-token-from-step-1",
    "phone_number": "+1234567890",
    "domain": "example.com"
}

Response:

{"status": "authenticated", "refresh": "...", "access": "..."}

Frontend Widget Setup

Add the Telegram Login Widget to your frontend:

<script async src="https://telegram.org/js/telegram-widget.js?22"
        data-telegram-login="your_bot_username"
        data-size="large"
        data-onauth="onTelegramAuth(user)"
        data-request-access="write">
</script>
<script>
function onTelegramAuth(user) {
    fetch('/moses/token/telegram/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({...user, domain: 'example.com'})
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'authenticated') {
            // Store JWT tokens
        } else if (data.status === 'phone_required') {
            // Show phone number form, then POST to /moses/token/telegram/complete/
        }
    });
}
</script>

Signals

Moses emits Django signals during credential confirmation workflows. You can listen to these signals in your application to perform custom actions.

Available Signals

phone_number_confirmed

Emitted when a user successfully confirms their phone number.

Parameters:

  • sender: The User model class
  • user: The user instance whose phone was confirmed
  • phone_number: The confirmed phone number (str)
  • is_initial_confirmation: True if this is the first confirmation, False if updating phone number

Example usage:

from django.dispatch import receiver
from moses.signals import phone_number_confirmed
from moses.models import CustomUser

@receiver(phone_number_confirmed, sender=CustomUser)
def handle_phone_confirmed(sender, user, phone_number, is_initial_confirmation, **kwargs):
    if is_initial_confirmation:
        print(f"User {user.id} confirmed their phone: {phone_number}")
    else:
        print(f"User {user.id} changed their phone to: {phone_number}")

email_confirmed

Emitted when a user successfully confirms their email address.

Parameters:

  • sender: The User model class
  • user: The user instance whose email was confirmed
  • email: The confirmed email address (str)
  • is_initial_confirmation: True if this is the first confirmation, False if updating email

Example usage:

from django.dispatch import receiver
from moses.signals import email_confirmed
from moses.models import CustomUser

@receiver(email_confirmed, sender=CustomUser)
def handle_email_confirmed(sender, user, email, is_initial_confirmation, **kwargs):
    if is_initial_confirmation:
        print(f"User {user.id} confirmed their email: {email}")
    else:
        print(f"User {user.id} changed their email to: {email}")

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_moses-0.15.0.tar.gz (32.6 kB view details)

Uploaded Source

Built Distribution

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

django_moses-0.15.0-py3-none-any.whl (44.4 kB view details)

Uploaded Python 3

File details

Details for the file django_moses-0.15.0.tar.gz.

File metadata

  • Download URL: django_moses-0.15.0.tar.gz
  • Upload date:
  • Size: 32.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.8 Darwin/25.3.0

File hashes

Hashes for django_moses-0.15.0.tar.gz
Algorithm Hash digest
SHA256 9958033d34ecbcf4a2c81ff81efb04b51b53650d911b33366b54d9a988242139
MD5 7198ad8c86fdf99d277a6adceeddb650
BLAKE2b-256 502be36fa9796d9f63644e0ed1954eff5347c6565adb6c2d1b3b2d3ff14a50f8

See more details on using hashes here.

File details

Details for the file django_moses-0.15.0-py3-none-any.whl.

File metadata

  • Download URL: django_moses-0.15.0-py3-none-any.whl
  • Upload date:
  • Size: 44.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.8 Darwin/25.3.0

File hashes

Hashes for django_moses-0.15.0-py3-none-any.whl
Algorithm Hash digest
SHA256 de18e251fd21ba8ac8f0f73be1068cdfdb2f7306072546de6f5177e9b20ad681
MD5 3e1c9211510de8fa55265f7feaca038d
BLAKE2b-256 8b8ade95e1070a7eb71b0a03ed9bdbd023f0130d69fe1a9681b5afa53c4e2bf2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page