Security python Advanced

TOTP Two-Factor Auth

Generate and verify time-based one-time passwords (TOTP) compatible with Google Authenticator.

python
import pyotp, qrcode, io, base64

def generate_totp_secret() -> str:
    return pyotp.random_base32()

def get_qr_code(secret: str, email: str, issuer: str = "NexDevTeam") -> str:
    uri = pyotp.totp.TOTP(secret).provisioning_uri(name=email, issuer_name=issuer)
    img = qrcode.make(uri)
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()

def verify_totp(secret: str, token: str) -> bool:
    return pyotp.TOTP(secret).verify(token, valid_window=1)

Prerequisites

  • pyotp >= 2.9
  • qrcode
  • pillow

Pro Tips

  • → Store the secret encrypted — it's equivalent to a password.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Advanced
Read time
4 min
Published
Sep 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.