djangodjango-rest-frameworktotp

How to set an advanced one time sms code in Django app


I have sms autentication in my Django app. I works right. But I want to use a recomendations from https://github.com/WICG/sms-one-time-codes So, instead of 4 digits code I want user to get smth like this: https://example.com, 747723, 747723 is your ExampleCo authentication code

**

"https://example.com" is the origin the code is associated with

"747723" is the code

"747723 is your ExampleCo authentication code.\n\n" is human-readable explanatory text.

services.py

from pyotp import HOTP
from django.db.models import F

def make_totp(user: User) -> str:
    totp = HOTP(user.otp_secret, digits=4)
    totp_code = totp.at(user.otp_counter)
    return totp_code

def totp_verify(user: User, totp_code: str, verify=None) -> bool:
    if user:
        totp = HOTP(user.otp_secret, digits=4)
        verify = totp.verify(otp=totp_code, counter=user.otp_counter)
        if verify:
            user.otp_counter = F("otp_counter") + 1
            user.save()
    return verify

Any suggestions how to solve this problem?


Solution

  • The solution:

    views.py

    from django.conf import settings
    
    code = make_totp(user=user)
    if settings.DEBUG:
        result = send_sms(phone=user.phone, totp_code=f"{code} - https://example.com, {code}, {code} is your ExampleCo authentication code")
    else:
        result = send_sms(phone=user.phone, totp_code=f"{code} - https://example.com, {code}, {code} is your ExampleCo authentication code")