|
| 1 | +"""This module provides functionality for generating a QR code for TOTP (Time-based One-Time Password) setup.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import warnings |
| 5 | + |
| 6 | +from dataclasses import dataclass |
| 7 | + |
| 8 | +try: |
| 9 | + import pyotp |
| 10 | +except (ImportError, ModuleNotFoundError): |
| 11 | + raise ImportError( |
| 12 | + "pyotp is required for OTP functionality. Please install it via 'pip install pyotp'." |
| 13 | + ) |
| 14 | + |
| 15 | +try: |
| 16 | + import qrcode |
| 17 | +except (ImportError, ModuleNotFoundError): |
| 18 | + raise ImportError( |
| 19 | + "qrcode is required for OTP functionality. Please install it via 'pip install qrcode[pil]'." |
| 20 | + ) |
| 21 | + |
| 22 | + |
| 23 | +def getenv(key: str, default: str | None = None) -> str | None: |
| 24 | + """Gets an environment variable or returns a default value. |
| 25 | +
|
| 26 | + Args: |
| 27 | + key: The environment variable key. |
| 28 | + default: The default value to return if the key is not found. |
| 29 | + Returns: |
| 30 | + The value of the environment variable or the default value. |
| 31 | + """ |
| 32 | + return os.environ.get(key.upper()) or os.environ.get(key.lower()) or default |
| 33 | + |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class OTPConfig: |
| 37 | + secret: str |
| 38 | + qr_filename: str |
| 39 | + authenticator_user: str |
| 40 | + authenticator_app: str |
| 41 | + |
| 42 | + |
| 43 | +config = OTPConfig( |
| 44 | + secret="", |
| 45 | + qr_filename=getenv("authenticator_qr_filename", "totp_qr.png"), |
| 46 | + authenticator_user=getenv("authenticator_user", "thevickypedia"), |
| 47 | + authenticator_app=getenv("authenticator_app", "FileBrowser"), |
| 48 | +) |
| 49 | + |
| 50 | + |
| 51 | +def display_secret() -> None: |
| 52 | + """Displays the TOTP secret key.""" |
| 53 | + try: |
| 54 | + term_size = os.get_terminal_size().columns |
| 55 | + except OSError: |
| 56 | + term_size = 120 |
| 57 | + base = "*" * term_size |
| 58 | + print( |
| 59 | + f"\n{base}\n" |
| 60 | + f"\nYour TOTP secret key is: {config.secret}" |
| 61 | + f"\nStore this key as the environment variable `authenticator_token`\n" |
| 62 | + f"\nQR code saved as {config.qr_filename!r} (you can scan this with your Authenticator app).\n" |
| 63 | + f"\n{base}", |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +def generate_qr() -> None: |
| 68 | + """Generates a QR code for TOTP setup.""" |
| 69 | + if getenv("authenticator_token"): |
| 70 | + warnings.warn( |
| 71 | + "\n\nAuthenticator token already set — skipping OTP setup. " |
| 72 | + "To create a new one, remove the 'authenticator_token' environment variable.\n", |
| 73 | + UserWarning, |
| 74 | + ) |
| 75 | + return |
| 76 | + |
| 77 | + # STEP 1: Generate a new secret key for the user (store this securely!) |
| 78 | + secret = pyotp.random_base32() |
| 79 | + |
| 80 | + # STEP 2: Create a provisioning URI (for the QR code) |
| 81 | + uri = pyotp.TOTP(secret).provisioning_uri( |
| 82 | + name=str(config.authenticator_user), issuer_name=config.authenticator_app |
| 83 | + ) |
| 84 | + |
| 85 | + # STEP 3: Generate a QR code (scan this with your authenticator app) |
| 86 | + qr = qrcode.make(uri) |
| 87 | + # Save the QR code |
| 88 | + qr.save(config.qr_filename) |
| 89 | + |
| 90 | + # STEP 4: Update the config with the new secret |
| 91 | + config.secret = secret |
| 92 | + display_secret() |
| 93 | + |
| 94 | + |
| 95 | +if __name__ == "__main__": |
| 96 | + generate_qr() |
0 commit comments