Two-Factor Authentication with Authy, Python and Flask

Download the Code

This Flask sample application is an example of typical login flow. To run this sample app yourself, download the code and follow the instructions on GitHub.

Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication determines the identity of a user by validating once by logging into the app, and then a second time with their mobile device using Authy.

For the second factor, we will validate that the user has their mobile phone by either:

  • Sending them a OneTouch push notification to their mobile Authy app or
  • Sending them a token through their mobile Authy app or
  • Sending them a one-time token in a text message sent with Authy via Twilio.

Here's how this works at a high level:

2FA High Level

See how VMware uses Authy 2FA to secure their enterprise mobility management solution.

Configuring Authy

If you haven't already, now is the time to sign up for Authy. Create your first application, naming it whatever you wish. After you create your application, your production API key will be visible on your dashboard:

Authy Dashboard

Once we have an Authy API key, we store it in our .env file, which helps us set the environment variables for our app.

You'll also want to set a callback URL for your application in the OneTouch section of the Authy dashboard. See the project README for more details.

Loading Code Samples...
Language
# Environment variables for authy2fa-flask

# Secret key (used for sessions)
export SECRET_KEY=not-so-secret

# Database
export DATABASE_URL=postgresql://localhost/2fa_flask

# Authy API Key
# Found at https://dashboard.authy.com under your application
export AUTHY_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
authy2fa-flask/.env_example
Environment Variable Settings

authy2fa-flask/.env_example

Now that we've configured our Flask app, let's take a look at how we register a user with Authy.

Register a User with Authy

When a new user signs up for our website we call this helper function, which handles storing the user in the database as well as registering the user with Authy.

In order to get a user set up for your application you will need their emailphone number and country code. We have fields for each of these on our sign up form.

Once we register the user with Authy we can get the user's Authy id off the response. This is very important — it's how we will verify the identity of our user with Authy.

Loading Code Samples...
Language
from authy.api import AuthyApiClient
from flask import current_app

from . import db
from .models import User


def get_authy_client():
    """Returns an AuthyApiClient"""
    return AuthyApiClient(current_app.config['AUTHY_API_KEY'])

def create_user(form):
    """Creates an Authy user and then creates a database User"""
    client = get_authy_client()

    # Create a new Authy user with the data from our form
    authy_user = client.users.create(form.email.data,
                                     form.phone_number.data,
                                     form.country_code.data)

    # If the Authy user was created successfully, create a local User
    # with the same information + the Authy user's id
    if authy_user.ok():
        user = User(form.email.data, form.password.data, form.name.data,
                    form.country_code.data, form.phone_number.data,
                    authy_user.id)

        # Save the user
        db.session.add(user)
        db.session.commit()
        db.session.refresh(user)
    return user

def send_authy_token_request(authy_user_id):
    """
    Sends a request to Authy to send a SMS verification code to a user's phone
    """
    client = get_authy_client()

    client.users.request_sms(authy_user_id)

def verify_authy_token(authy_user_id, user_entered_code):
    """Verifies a user-entered token with Authy"""
    client = get_authy_client()

    return client.tokens.verify(authy_user_id, user_entered_code)
twofa/utils.py
Create and Register a User with Authy

twofa/utils.py

Next up, let's take a look at the login.

Log in with Authy OneTouch

When a user attempts to log in to our website, we will ask them for a second form of identification. Let's take a look at OneTouch verification first.

Authy OneTouch Approval

OneTouch works like so:

  • We attempt to send a OneTouch Approval Request to the user
  • If the user has OneTouch enabled, we will get a success message back
  • The user hits Approve in their Authy app
  • Authy makes a POST request to our app with an approved status
  • We log the user in
Loading Code Samples...
Language
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
twofa/auth/views.py
Log in with Authy OneTouch

twofa/auth/views.py

Send the OneTouch Request

When our user logs in we immediately attempt to verify their identity with OneTouch. We will fall back gracefully if they don't have a OneTouch device, but we don't know until we try.

Authy lets us pass extra details with our OneTouch request including a message, a logo, and any other details we want to send. We could easily send any number of details by appending details[some_detail] to our POST request. You could imagine a scenario where we send a OneTouch request to approve a money transfer:

data = {
    'api_key': client.api_key,
    'message': "Request to send money to Jarod's vault",
    'details[Request From]': 'Jarod',
    'details[Amount Requested]': '1,000,000',
    'details[Currency]': 'Galleons'
}
Loading Code Samples...
Language
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash

import requests

from . import db


class User(db.Model):
    """
    Represents a single user in the system.
    """
    __tablename__ = 'users'

    AUTHY_STATUSES = (
        'unverified',
        'onetouch',
        'sms',
        'token',
        'approved',
        'denied'
    )

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    full_name = db.Column(db.String(256))
    country_code = db.Column(db.Integer)
    phone = db.Column(db.String(30))
    authy_id = db.Column(db.Integer)
    authy_status = db.Column(db.Enum(*AUTHY_STATUSES, name='authy_statuses'))

    def __init__(self, email, password, full_name, country_code,
                 phone, authy_id, authy_status='approved'):
        self.email = email
        self.password = password
        self.full_name = full_name
        self.country_code = country_code
        self.phone = phone
        self.authy_id = authy_id
        self.authy_status = authy_status

    def __repr__(self):
        return '<User %r>' % self.email

    @property
    def password(self):
        raise AttributeError('password is not readable')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def send_one_touch_request(self):
        """Initiates an Authy OneTouch request for this user"""
        # Importing here to avoid circular dependency
        from .utils import get_authy_client
        client = get_authy_client()

        url = '{0}/onetouch/json/users/{1}/approval_requests'.format(client.api_uri, self.authy_id)
        data = {
            'api_key': client.api_key,
            'message': 'Request to log in to Twilio demo app',
            'details[Email]': self.email
        }
        response = requests.post(url, data=data)
        json_response = response.json()

        if 'approval_request' in json_response:
            self.authy_status = 'onetouch'
        else:
            self.authy_status = 'sms'

        db.session.add(self)
        db.session.commit()

        return json_response
twofa/models.py
Send the OneTouch Request

twofa/models.py

Once we send the request we update our user's authy_status based on the response. This lets us know which method Authy will try first to verify this request with our user. But first we have to register a OneTouch callback endpoint.

Configure the OneTouch callback

In order for our app to know what the user did after we sent the OneTouch request, we need to register a callback endpoint with Authy.

Authy OneTouch Callback

Note: In order to verify that the request is coming from Authy we've written a decorator, @verify_authy_request, that will halt the request if we cannot verify that it actually came from Authy.

Here in our callback, we look up the user using the authy_id sent with the Authy POST request. In a production application we might use a websocket to let our client know that we received a response from Authy. For this version, we keep it simple and update the authy_status on the user. Our client-side code will check that field before completing the login.

Loading Code Samples...
Language
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
twofa/auth/views.py
Update user status using Authy Callback

twofa/auth/views.py

Let's take a look at that client-side code now.

Handle Two-Factor Asyncronously

In order for two-factor authentication to be seamless, it is best done asynchronously so that the user doesn't even know it's happening.

We've already taken a look at what's happening on the server side, so let's step in front of the cameras now and see how our JavaScript is interacting with those server endpoints.

First we hijack the login form submit and pass the data to our sessions/create controller using Ajax. Depending on how that endpoint responds, we will either wait for a OneTouch response or ask the user to enter a token.

If we expect a OneTouch response, we will begin polling /login/status until we see the OneTouch login was either approved or denied.

Loading Code Samples...
Language
$(document).ready(function() {

  $('#login-form').submit(function(e) {
    e.preventDefault();
    formData = $(e.currentTarget).serialize();
    attemptOneTouchVerification(formData);
  });

  var attemptOneTouchVerification = function(form) {
    $.post( "/login", form, function(data) {
      // Check first if we successfully authenticated the username and password
      if (data.hasOwnProperty('invalid_credentials')) {
        $('.form-errors').remove();
        $('#login-form').prepend(data.invalid_credentials);
        return;
      }

      if (data.success) {
        $('#authy-modal').modal({backdrop:'static'},'show');
        $('.auth-ot').fadeIn();
        checkForOneTouch();
      } else {
        redirectToTokenForm();
      }
    });
  };

  var checkForOneTouch = function() {
    $.get( "/login/status", function(data) {
      
      if (data == 'approved') {
        window.location.href = "/account";
      } else if (data == 'denied') {
        redirectToTokenForm();
      } else {
        setTimeout(checkForOneTouch, 2000);
      }
    });
  };

  var redirectToTokenForm = function() {
    window.location.href = "/verify";
  };
});
twofa/static/js/sessions.js
Handle Two-Factor Asynchronously

twofa/static/js/sessions.js

Now let's see how to handle the case where we receive a denied OneTouch response.

Fall back to a Token

This is the endpoint that our javascript is polling. It is waiting for the user's authy_status to be either approved or denied. If the user approves the OneTouch request, our JavaScript code from the previous step will redirect their browser to their account screen.

If the OneTouch request was denied, we will ask the user to log in with a token instead.

Loading Code Samples...
Language
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
twofa/auth/views.py
Handle Login Status

twofa/auth/views.py

Now let's see how to send a token to the user.

Send a Token

This view is responsible for sending the token and then validating the code that our user enters.

In the case where our user already has the Authy app but is not enabled for OneTouch, this same method will trigger a push notification that will be sent to their phone with a code inside the Authy app.

The user will see a verification form that looks like this:

The Verification Form

A POST request to this view validates the code our user enters. First, we grab the User model by the ID we stored in the session. Next, we use the Authy API to validate the code our user entered against the one Authy sent them.


If the two match, our login process is complete! We mark the user's authy_status as approved and thank them for using two-factor authentication.

Loading Code Samples...
Language
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
twofa/auth/views.py
Verify users via Authy Token

twofa/auth/views.py

That's it! We've just implemented two-factor auth using three different methods and the latest in Authy technology.

Where to next?

If you're a Python developer working with Twilio, you might enjoy these other tutorials:

SMS and MMS Notifications

Faster than e-mail and less likely to get blocked, text messages are great for timely alerts and notifications. Learn how to send out SMS (and MMS) notifications to a list of server administrators.

Call Tracking

Call Tracking helps you measure the effectiveness of different marketing campaigns. By assigning a unique phone number to different advertisements, you can track which ones have the best call rates and get some data about the callers themselves.

Did this help?

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Connect with us on Twitter and let us know what you build!

Andrew Baker
Kat King
Agustin Camino

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
# Environment variables for authy2fa-flask

# Secret key (used for sessions)
export SECRET_KEY=not-so-secret

# Database
export DATABASE_URL=postgresql://localhost/2fa_flask

# Authy API Key
# Found at https://dashboard.authy.com under your application
export AUTHY_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
from authy.api import AuthyApiClient
from flask import current_app

from . import db
from .models import User


def get_authy_client():
    """Returns an AuthyApiClient"""
    return AuthyApiClient(current_app.config['AUTHY_API_KEY'])

def create_user(form):
    """Creates an Authy user and then creates a database User"""
    client = get_authy_client()

    # Create a new Authy user with the data from our form
    authy_user = client.users.create(form.email.data,
                                     form.phone_number.data,
                                     form.country_code.data)

    # If the Authy user was created successfully, create a local User
    # with the same information + the Authy user's id
    if authy_user.ok():
        user = User(form.email.data, form.password.data, form.name.data,
                    form.country_code.data, form.phone_number.data,
                    authy_user.id)

        # Save the user
        db.session.add(user)
        db.session.commit()
        db.session.refresh(user)
    return user

def send_authy_token_request(authy_user_id):
    """
    Sends a request to Authy to send a SMS verification code to a user's phone
    """
    client = get_authy_client()

    client.users.request_sms(authy_user_id)

def verify_authy_token(authy_user_id, user_entered_code):
    """Verifies a user-entered token with Authy"""
    client = get_authy_client()

    return client.tokens.verify(authy_user_id, user_entered_code)
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash

import requests

from . import db


class User(db.Model):
    """
    Represents a single user in the system.
    """
    __tablename__ = 'users'

    AUTHY_STATUSES = (
        'unverified',
        'onetouch',
        'sms',
        'token',
        'approved',
        'denied'
    )

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    full_name = db.Column(db.String(256))
    country_code = db.Column(db.Integer)
    phone = db.Column(db.String(30))
    authy_id = db.Column(db.Integer)
    authy_status = db.Column(db.Enum(*AUTHY_STATUSES, name='authy_statuses'))

    def __init__(self, email, password, full_name, country_code,
                 phone, authy_id, authy_status='approved'):
        self.email = email
        self.password = password
        self.full_name = full_name
        self.country_code = country_code
        self.phone = phone
        self.authy_id = authy_id
        self.authy_status = authy_status

    def __repr__(self):
        return '<User %r>' % self.email

    @property
    def password(self):
        raise AttributeError('password is not readable')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def send_one_touch_request(self):
        """Initiates an Authy OneTouch request for this user"""
        # Importing here to avoid circular dependency
        from .utils import get_authy_client
        client = get_authy_client()

        url = '{0}/onetouch/json/users/{1}/approval_requests'.format(client.api_uri, self.authy_id)
        data = {
            'api_key': client.api_key,
            'message': 'Request to log in to Twilio demo app',
            'details[Email]': self.email
        }
        response = requests.post(url, data=data)
        json_response = response.json()

        if 'approval_request' in json_response:
            self.authy_status = 'onetouch'
        else:
            self.authy_status = 'sms'

        db.session.add(self)
        db.session.commit()

        return json_response
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
$(document).ready(function() {

  $('#login-form').submit(function(e) {
    e.preventDefault();
    formData = $(e.currentTarget).serialize();
    attemptOneTouchVerification(formData);
  });

  var attemptOneTouchVerification = function(form) {
    $.post( "/login", form, function(data) {
      // Check first if we successfully authenticated the username and password
      if (data.hasOwnProperty('invalid_credentials')) {
        $('.form-errors').remove();
        $('#login-form').prepend(data.invalid_credentials);
        return;
      }

      if (data.success) {
        $('#authy-modal').modal({backdrop:'static'},'show');
        $('.auth-ot').fadeIn();
        checkForOneTouch();
      } else {
        redirectToTokenForm();
      }
    });
  };

  var checkForOneTouch = function() {
    $.get( "/login/status", function(data) {
      
      if (data == 'approved') {
        window.location.href = "/account";
      } else if (data == 'denied') {
        redirectToTokenForm();
      } else {
        setTimeout(checkForOneTouch, 2000);
      }
    });
  };

  var redirectToTokenForm = function() {
    window.location.href = "/verify";
  };
});
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))
from authy import AuthyApiException
from flask import flash, jsonify, redirect, render_template, request, session, url_for

from . import auth
from .forms import LoginForm, SignUpForm, VerifyForm
from .. import db
from ..decorators import login_required, verify_authy_request
from ..models import User
from ..utils import create_user, send_authy_token_request, verify_authy_token


@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    """Powers the new user form"""
    form = SignUpForm(request.form)

    if form.validate_on_submit():
        try:
            user = create_user(form)
            session['user_id'] = user.id

            return redirect(url_for('main.account'))

        except AuthyApiException:
            form.errors['Authy API'] = ['There was an error creating the Authy user']

    return render_template('signup.html', form=form)

@auth.route('/login', methods=['GET', 'POST'])
def log_in():
    """
    Powers the main login form.

    - GET requests render the username / password form
    - POST requests process the form data via an AJAX request triggered in the
      user's browser
    """
    form = LoginForm(request.form)

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            session['user_id'] = user.id

            # Send a request to verify this user's login with OneTouch
            one_touch_response = user.send_one_touch_request()

            return jsonify(one_touch_response)
        else:
            # The username and password weren't valid
            form.errors['Invalid credentials'] = ['The username and password combination you entered are invalid']

    if request.method == 'POST':
        # This was an AJAX request, and we should return our form errors as JSON
        return jsonify({'invalid_credentials': render_template('_login_error.html', form=form)})
    else:
        return render_template('login.html', form=form)

@auth.route('/authy/callback', methods=['POST'])
@verify_authy_request
def authy_callback():
    """Authy uses this endpoint to tell us the result of a OneTouch request"""
    authy_id = request.json.get('authy_id')
    # When you're configuring your Endpoint/URL under OneTouch settings '1234'
    # is the preset 'authy_id'
    if authy_id != '1234':
        user = User.query.filter_by(authy_id=authy_id).one()

        user.authy_status = request.json.get('status')
        db.session.add(user)
        db.session.commit()

    return ('', 204)

@auth.route('/login/status')
def login_status():
    """
    Used by AJAX requests to check the OneTouch verification status of a user
    """
    user = User.query.get(session['user_id'])
    return user.authy_status

@auth.route('/verify', methods=['GET', 'POST'])
@login_required
def verify():
    """Powers token validation (not using OneTouch)"""
    form = VerifyForm(request.form)
    user = User.query.get(session['user_id'])

    # Send a token to our user when they GET this page
    if request.method == 'GET':
        send_authy_token_request(user.authy_id)

    if form.validate_on_submit():
        user_entered_code = form.verification_code.data

        verified = verify_authy_token(user.authy_id, str(user_entered_code))
        if verified.ok():
            user.authy_status = 'approved'
            db.session.add(user)
            db.session.commit()

            flash("You're logged in! Thanks for using two factor verification.", 'success')
            return redirect(url_for('main.account'))
        else:
            form.errors['verification_code'] = ['Code invalid - please try again.']

    return render_template('verify.html', form=form)

@auth.route('/resend', methods=['POST'])
@login_required
def resend():
    """Resends a verification token to a user"""
    user = User.query.get(session.get('user_id'))
    send_authy_token_request(user.authy_id)
    flash('I just re-sent your verification code - enter it below.', 'info')
    return redirect(url_for('auth.verify'))

@auth.route('/logout')
def log_out():
    """Log out a user, clearing their session variables"""
    session.pop('user_id', None)

    flash("You're now logged out! Thanks for visiting.", 'info')
    return redirect(url_for('main.home'))