Moses
Moses is the Django app that provides OTP authentication and phone number email verification by 6-digit verification codes.
Quick start
- Add "moses" to your INSTALLED_APPS setting like this::
INSTALLED_APPS = [
...
'moses',
'django.contrib.admin',
...
'social_django',
]
- Set moses's CustomUser model as AUTH_USER_MODEL::
AUTH_USER_MODEL = 'moses.CustomUser'
- Allow OTP header in django-cors-headers config::
CORS_ALLOW_HEADERS = (
*default_headers,
"otp",
)
- Add MFAModelBackend as Authentication backend to process OTP on authentication::
AUTHENTICATION_BACKENDS = [
'social_core.backends.google.GoogleOAuth2',
'moses.authentication.MFAModelBackend',
...
]
- Add JWTAuthentication to REST_FRAMEWORK's DEFAULT_AUTHENTICATION_CLASSES::
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'moses.authentication.JWTAuthentication',
]
}
- 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")),
),
}
- 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')),
]
-
Run
python manage.py migrateto create the accounts models. -
Add middleware:
MIDDLEWARE = [
...
'social_django.middleware.SocialAuthExceptionMiddleware',
]
- Add context processors:
TEMPLATES[0]['OPTIONS']['context_processors'] += [
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
]
Google Sign-In
Moses supports authentication via Google OAuth2. To enable it:
-
Create a Google OAuth2 Client ID in the Google Cloud Console.
-
Add the client ID to your
MOSESsettings:
MOSES = {
...
"GOOGLE_OAUTH2_CLIENT_ID": "your-google-client-id.apps.googleusercontent.com",
}
- The following endpoints will be available:
-
POST
/moses/token/google/— Step 1: Send the Googleid_tokenanddomain. If the user exists, returns JWT tokens. If the user is new, returns a temporarygoogle_auth_tokenfor completing registration.Request body:
{"id_token": "<google-id-token>", "domain": "example.com"}
-
POST
/moses/token/google/complete/— Step 2 (new users only): Send thegoogle_auth_token,phone_number, anddomainto create the account and receive JWT tokens.Request body:
{"google_auth_token": "<temp-token>", "phone_number": "+1234567890", "domain": "example.com"}
Telegram Sign-In
Moses supports authentication via the Telegram Login Widget — the method officially recommended by Telegram.
Setup
-
Create a Telegram bot via @BotFather.
-
In BotFather, go to Bot Settings → Domain → Add your website domain to allow login from your site.
-
Add the bot token to your
MOSESsettings:
MOSES = {
...
"TELEGRAM_BOT_TOKEN": "123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ",
}
- Optional settings:
MOSES = {
...
"TELEGRAM_AUTH_TEMP_TOKEN_EXPIRY_MINUTES": 5, # temp token lifetime for new user registration (default: 5)
"TELEGRAM_AUTH_DATA_MAX_AGE_SECONDS": 300, # max age of Telegram auth data to prevent replay attacks (default: 300 = 5min)
}
- Add the Telegram Login Widget to your frontend. The widget will return auth data containing:
id,first_name,last_name,username,photo_url,auth_date, andhash.
API Endpoints
-
POST
/moses/token/telegram/— Step 1: Send the Telegram auth data anddomain. If the user exists (bytelegram_id), returns JWT tokens. If the user is new, returns a temporarytelegram_auth_tokenfor completing registration.Request body:
{ "auth_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 (existing user):
{"status": "authenticated", "refresh": "<jwt>", "access": "<jwt>"}
Response (new user):
{ "status": "phone_required", "telegram_auth_token": "<temp-token>", "first_name": "John", "last_name": "Doe", "username": "johndoe" }
-
POST
/moses/token/telegram/complete/— Step 2 (new users only): Send thetelegram_auth_token,phone_number, optionalemail, anddomainto create the account and receive JWT tokens.Request body:
{ "telegram_auth_token": "<temp-token>", "phone_number": "+1234567890", "email": "john@example.com", "domain": "example.com" }
Response:
{"status": "authenticated", "refresh": "<jwt>", "access": "<jwt>"}
How Verification Works
Moses verifies Telegram auth data using the algorithm specified by Telegram:
- A SHA-256 hash of the bot token is used as the HMAC secret key.
- All auth data fields (except
hash) are sorted alphabetically and joined askey=value\n. - An HMAC-SHA-256 signature is computed and compared against the received
hash. - The
auth_dateis checked to prevent replay attacks.
Message templates (SMS / email)
All outgoing SMS and email texts are configurable through the MESSAGE_TEMPLATES
setting — the same way the SMS transport is provided via SEND_SMS_HANDLER. You
override any subset of the keys; the rest fall back to the built-in defaults.
from django.utils.translation import gettext_lazy as _
MOSES = {
...
"MESSAGE_TEMPLATES": {
# business requirement: SMS must contain only the code
"PHONE_NUMBER_CONFIRMATION_PIN_BODY": "{pin}",
"PASSWORD_RESET_SMS_BODY": "{pin}",
# a localizable email body (needs your own .po/.mo — see i18n below)
"EMAIL_CONFIRMATION_PIN_BODY": _("Hi {user.first_name}! Your code is {pin}"),
},
}
Available keys
| Key | Channel | Placeholders |
|---|---|---|
EMAIL_CONFIRMATION_PIN_TITLE |
email subject | {pin} |
EMAIL_CONFIRMATION_PIN_BODY |
email body | {pin} |
PHONE_NUMBER_CONFIRMATION_PIN_BODY |
SMS | {pin} |
PASSWORD_RESET_PIN_TITLE |
email subject | {pin} |
PASSWORD_RESET_EMAIL_BODY |
email body | {pin} |
PASSWORD_RESET_SMS_BODY |
SMS | {pin} |
PASSWORD_CHANGED_TITLE / PASSWORD_CHANGED_BODY |
{domain} |
|
EMAIL_CHANGED_TITLE / EMAIL_CHANGED_BODY |
{domain} |
|
PHONE_NUMBER_CHANGED_TITLE / PHONE_NUMBER_CHANGED_BODY |
{domain} |
Password reset uses separate SMS and email bodies, so you can strip the SMS to a bare code while keeping the full email text.
Placeholders
Templates are rendered with str.format. Always available: {pin}, {user} (and
its attributes, e.g. {user.first_name}, {user.email}), and {domain}. Escape
literal braces as {{ / }}; referencing an undefined placeholder raises
KeyError (surfacing the misconfiguration).
Internationalization
Each template is resolved to the user's preferred_language before formatting.
- A plain string (e.g.
"{pin}") is not translated — the same in every language. This is exactly what you want for an SMS that is only a code. - To translate a template, wrap it in
gettext_lazyand ship your own.po/.mocatalogs (setLOCALE_PATHS, runmakemessages+compilemessages). Moses does not ship translation catalogs itself, so the built-in defaults render as their English source text until you provide your own.
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 classuser: The user instance whose phone was confirmedphone_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 classuser: The user instance whose email was confirmedemail: 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}")
Phone OTP login
Opt-in passwordless login by SMS code. Off by default; with the flag off nothing changes.
Run migrate after upgrading to 0.18.0 (migration 0007_email_unique_unless_blank: (site, email) is unique only when the email is non-blank).
MOSES = {
...
'PHONE_OTP_LOGIN': True,
'PHONE_OTP_REQUEST_IP_LIMIT': (20, 3600), # optional: (count, seconds) per client IP, default None
'PHONE_OTP_CODES_PER_PHONE_LIMIT': (3, 86400), # optional: codes sent per (site, phone), default None
}
POST /moses/users/otp_request/ {"phone_number": "+996...", "domain": "example.com"} -> {}.
Creates the user (unusable password) if the number is new and sends a code; an inactive user gets the same {} but no
code. A blank, too long (over 20 chars) or validator-rejected number gives 400 invalid_phone_number; an unknown domain
gives 400 site_with_domain_does_not_exist. too_frequent_sms_requests is 400 for the per-phone resend pause
(PHONE_NUMBER_CONFIRMATION_SMS_SECONDS_PERIOD) and 429 over PHONE_OTP_REQUEST_IP_LIMIT. Over
PHONE_OTP_CODES_PER_PHONE_LIMIT the answer is 429 phone_otp_codes_limit_reached; only codes actually sent count.
POST /moses/users/otp_verify/ {"phone_number": "+996...", "code": "123456", "domain": "example.com"} -> {"access": "...", "refresh": "...", "created": true}.
created is true exactly when this verify did the user's initial phone confirmation (the same moment
phone_number_confirmed fires with is_initial_confirmation=True), so a client can show a one-time onboarding prompt
for brand-new accounts; false for every later login. A failed TOTP doesn't confirm, so the next success still says true.
A wrong or unknown code gives 400 {"code": [incorrect_confirmation_pin]}; too many attempts give attempts_limit_reached.
A superuser or a user with an MFA key must also send "otp" (their TOTP); a missing or wrong one gives 400
{"otp": [invalid_otp]}, costs an attempt and keeps the SMS code valid. A superuser without an MFA key can't log in
this way. There is no DEBUG master code. phone_number_confirmed receivers run inside the verify transaction, under a
row lock on the user: keep them quick, and an exception in one fails the login.
While the flag is on, these return 404: user create (POST /moses/users/), set_password, reset_password,
reset_password_confirm, self-deletion (DELETE /moses/users/me/ and DELETE /moses/users/{id}/; it is gated by
current_password) and the password token endpoint (token_obtain_pair). Django admin login is unchanged.
Both limits count in Django's cache, so it must be shared and atomic (Redis or Memcached); LocMem is per process.
The per-IP limit uses IP_HEADER: it must be a header your reverse proxy overwrites (not one the client can set),
otherwise the limit can be bypassed by spoofing it. If IP_HEADER is set but missing on a request, REMOTE_ADDR is used.
Metadata
Release files for django-moses 0.18.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_moses-0.18.1.tar.gz | 42.7 kB | Without provenance | Details for django_moses-0.18.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_moses-0.18.1-py3-none-any.whl | Python 3 | none | any | Details for django_moses-0.18.1-py3-none-any.whl |
Total release size: 97.2 kB
Release files / django_moses-0.18.1.tar.gz
| Download URL | django_moses-0.18.1.tar.gz |
|---|---|
| Size | 42.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
81a59af3a956480f6ecea24a33569377d1afa9fc2e6210ce93a1c26f3caf174f
|
|
BLAKE2b-256 checksum How to use checksums |
2c13f48fbcef24805a536de9fd3020ad9ef80293fda0f69ed365d0dec0c30605
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.2.1 CPython/3.13.8 Darwin/27.0.0
|
Release files / django_moses-0.18.1-py3-none-any.whl
| Download URL | django_moses-0.18.1-py3-none-any.whl |
|---|---|
| Size | 54.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b15484cfa54a53bac1e5e03cfd54b9c9a816a610bb097a70d9ff95193c30b148
|
|
BLAKE2b-256 checksum How to use checksums |
43dcf307f6ba7f62c713ba642cc5d5a70d7660cceaa3c90fb0ad0cb8438dd612
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.2.1 CPython/3.13.8 Darwin/27.0.0
|
Security for django-moses 0.18.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.