Implementing Ensure in a simple OTP authentication flow.

Live demo

This example shows how to implement a simple OTP authentication flow with the Ensure compliance check done before allowing the user to enter.

This is the code on the server side.

import pyotp
from flask import Flask, render_template, request, flash, jsonify
import qrcode
from io import BytesIO
import base64

app = Flask(__name__)
app.secret_key = "your_secret_key_here"

# Generate a base32 secret
secret = pyotp.random_base32()

# Create a TOTP object
totp = pyotp.TOTP(secret)


@app.route("/", methods=["GET"])
def index():

    # Generate a QR code URI for the TOTP object
    qr_code_uri = totp.provisioning_uri("TOTP Demo", issuer_name="Ensure")
    img = qrcode.make(qr_code_uri)
    buffered = BytesIO()
    img.save(buffered)
    img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
    return render_template("index.html", qr_code_uri=f"data:image/png;base64,{img_str}")

@app.route("/auth", methods=["POST"])
def auth():
    if request.method == "POST":
        user_code = request.form.get("otp")
        if totp.verify(user_code):
            return jsonify({
                'ok': 1,
            })
        else:
            return jsonify({
                'ok': 0,
            })

if __name__ == "__main__":
    app.run(debug=True)

The html template and javascript looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TOTP Demo</title>
        <script src="https://v2.alertsec.com/assets/js/ensure.js"></script>
</head>
<body>
        <center>
            <h1>TOTP Demo</h1>
            <h2>1. Register account by scanning the QR code with your authenticator app:</h2>
            <img src="{{ qr_code_uri }}" alt="QR Code">

            <br/>
            <br/>
            <h2>2. Enter OTP token to validate:</h2>
            <form method="POST" id="otp_form">
                    <label for="otp">Enter the code from your authenticator app:</label>
                    <input type="text" name="otp" required>
                    <button type="submit">Verify</button>
            </form>
            <div id="message"></div>
        </center>

<script>
document.getElementById('otp_form').addEventListener('submit', async (event) => {
    event.preventDefault();

    Ensure.run("<CHANGE_ME>", "testuser").then((result) => {

        const form = event.target;
        const formData = new FormData(form);
        formData.append('ensure_token', result.token)
        const messageDiv = document.getElementById('message');

        messageDiv.innerHTML = 'Loading...';

        fetch('/auth', {
            method: 'POST',
            body: formData,
        }).then((result) => result.json()).then((result) => {
            if (result.ok) {
                messageDiv.innerHTML = 'Authentication success';
            } else {
                messageDiv.innerHTML = 'Authentication failed';
            }
        }).catch(error => {
            messageDiv.innerHTML = 'Error: ' + error.message;
        });
    })


});
</script>
</body>
</html>