Two-factor auth (2FA)

Standards-based TOTP โ€” no library, just the standard library.

class=kw>import larz.auth as auth, larz.twofa as twofa
auth.enable(app)
twofa.enable(app, issuer="MyApp")     class=com># attaches app.twofa + @app.twofa_required

Enrolment

begin() creates a pending secret and returns an otpauth:// URI to render as a QR code. The user scans it, types the code their app shows, and activate() turns 2FA on and returns one-time backup codes.

uri, secret = app.twofa.begin(req.user)      class=com># show `uri` as a QR
codes = app.twofa.activate(req.user, code)   class=com># -> list of backup codes, or None

At login

After the password step, if the user has 2FA enabled, challenge them for a code:

if app.twofa.is_enabled(user):
    if app.twofa.verify(user, code):         class=com># TOTP or an unused backup code
        app.twofa.mark_verified(req)         class=com># this session has passed 2FA

Gate sensitive routes

@app.twofa_required        class=com># redirects to the challenge if 2FA is on and not passed
@app.get("/billing")
class=kw>def billing(req): ...

Users without 2FA enabled pass straight through, so you can roll 2FA out gradually. verify_code(), now_code() and provisioning_uri() are also exported for custom flows. See the guide: TOTP 2FA in Python.