0

What is the easiest way to generate a one-time password (sms secret code with N lengths of symbols) with passlib?

How I'm creating it now:

from secrets import randbelow as secrets_randbelow


def create_secret_code() -> str:  # TODO use OTP
    secret_code = "".join([str(secrets_randbelow(exclusive_upper_bound=10)) for _ in range(config.SECRET_CODE_LEN)])
    print_on_stage(secret_code=secret_code)
    return secret_code

Obviously, it needs to check that generated code already not in a use (for example - making it via Redis).

I also already have an passlib object into my code to hashing and verifying passwords

from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

I found this class, but can't figure out how to just generate sms secret code with N lengths of symbols

P.S. I added a fastapi tag because I'm using an fastapi and passlib is used as standard cryptography tool for it, docs

Drdilyor
  • 1,250
  • 1
  • 12
  • 30
salius
  • 918
  • 1
  • 14
  • 30

1 Answers1

0

You can initialize the TOTP class with the number of digits you want for the token, like this:

TOTP(digits=10)

Here's a complete example, using your config.SECRET_CODE_LEN:

from passlib.totp import TOTP
otp = TOTP('s3jdvb7qd2r7jpxx', digits=config.SECRET_CODE_LEN)
token = otp.generate()
print(token.token)