Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Two-Factor Authentication with Authy, Python and Flask


(warning)

Warning

As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.

For new development, we encourage you to use the Verify v2 API.

Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see Migrating from Authy to Verify for SMS(link takes you to an external page).

This Flask(link takes you to an external page) sample application is an example of typical login flow. To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication(link takes you to an external page) 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(link takes you to an external page).

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.

See how VMware uses Authy 2FA to secure their enterprise mobility management solution.(link takes you to an external page)


Configuring Authy

configuring-authy page anchor

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

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(link takes you to an external page) for more details.

Environment Variable Settings

environment-variable-settings page anchor

authy2fa-flask/.env_example


_10
# Environment variables for authy2fa-flask
_10
_10
# Secret key (used for sessions)
_10
SECRET_KEY=not-so-secret
_10
_10
# Authy API Key
_10
# Found at https://dashboard.authy.com under your application
_10
AUTHY_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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

register-a-user-with-authy page anchor

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 email, phone 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.

Create and Register a User with Authy

create-and-register-a-user-with-authy page anchor

twofa/utils.py


_68
from authy.api import AuthyApiClient
_68
from flask import current_app
_68
from authy import AuthyApiException
_68
_68
_68
def get_authy_client():
_68
""" Return a configured Authy client. """
_68
return AuthyApiClient(current_app.config['AUTHY_API_KEY'])
_68
_68
_68
def create_user(form):
_68
"""Creates an Authy user and then creates a database User"""
_68
client = get_authy_client()
_68
_68
# Create a new Authy user with the data from our form
_68
authy_user = client.users.create(
_68
form.email.data, form.phone_number.data, form.country_code.data
_68
)
_68
_68
# If the Authy user was created successfully, create a local User
_68
# with the same information + the Authy user's id
_68
if authy_user.ok():
_68
return form.create_user(authy_user.id)
_68
else:
_68
raise AuthyApiException('', '', authy_user.errors()['message'])
_68
_68
_68
def send_authy_token_request(authy_user_id):
_68
"""
_68
Sends a request to Authy to send a SMS verification code to a user's phone
_68
"""
_68
client = get_authy_client()
_68
_68
client.users.request_sms(authy_user_id)
_68
_68
_68
def send_authy_one_touch_request(authy_user_id, email=None):
_68
"""Initiates an Authy OneTouch request for a user"""
_68
client = get_authy_client()
_68
_68
details = {}
_68
_68
if email:
_68
details['Email'] = email
_68
_68
response = client.one_touch.send_request(
_68
authy_user_id, 'Request to log in to Twilio demo app', details=details
_68
)
_68
_68
if response.ok():
_68
return response.content
_68
_68
_68
def verify_authy_token(authy_user_id, user_entered_code):
_68
"""Verifies a user-entered token with Authy"""
_68
client = get_authy_client()
_68
_68
return client.tokens.verify(authy_user_id, user_entered_code)
_68
_68
_68
def authy_user_has_app(authy_user_id):
_68
"""Verifies a user has the Authy app installed"""
_68
client = get_authy_client()
_68
authy_user = client.users.status(authy_user_id)
_68
try:
_68
return authy_user.content['status']['registered']
_68
except KeyError:
_68
return False

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


Log in with Authy OneTouch

log-in-with-authy-onetouch page anchor

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.

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

twofa/auth/views.py


_149
from authy import AuthyApiException
_149
from flask import flash, jsonify, redirect, render_template, request, session, url_for
_149
_149
from . import auth
_149
from .forms import LoginForm, SignUpForm, VerifyForm
_149
from ..database import db
_149
from ..decorators import login_required, verify_authy_request
_149
from ..models import User
_149
from ..utils import create_user, send_authy_token_request, verify_authy_token
_149
_149
_149
@auth.route('/sign-up', methods=['GET', 'POST'])
_149
def sign_up():
_149
"""Powers the new user form"""
_149
form = SignUpForm(request.form)
_149
_149
if form.validate_on_submit():
_149
try:
_149
user = create_user(form)
_149
session['user_id'] = user.id
_149
_149
return redirect(url_for('main.account'))
_149
_149
except AuthyApiException as e:
_149
form.errors['Authy API'] = [
_149
'There was an error creating the Authy user',
_149
e.msg,
_149
]
_149
_149
return render_template('signup.html', form=form)
_149
_149
_149
@auth.route('/login', methods=['GET', 'POST'])
_149
def log_in():
_149
"""
_149
Powers the main login form.
_149
_149
- GET requests render the username / password form
_149
- POST requests process the form data via an AJAX request triggered in the
_149
user's browser
_149
"""
_149
form = LoginForm(request.form)
_149
_149
if form.validate_on_submit():
_149
user = User.query.filter_by(email=form.email.data).first()
_149
if user is not None and user.verify_password(form.password.data):
_149
session['user_id'] = user.id
_149
_149
if user.has_authy_app:
_149
# Send a request to verify this user's login with OneTouch
_149
one_touch_response = user.send_one_touch_request()
_149
return jsonify(one_touch_response)
_149
else:
_149
return jsonify({'success': False})
_149
else:
_149
# The username and password weren't valid
_149
form.email.errors.append(
_149
'The username and password combination you entered are invalid'
_149
)
_149
_149
if request.method == 'POST':
_149
# This was an AJAX request, and we should return any errors as JSON
_149
return jsonify(
_149
{'error': render_template('_login_error.html', form=form)}
_149
) # noqa: E501
_149
else:
_149
return render_template('login.html', form=form)
_149
_149
_149
@auth.route('/authy/callback', methods=['POST'])
_149
@verify_authy_request
_149
def authy_callback():
_149
"""Authy uses this endpoint to tell us the result of a OneTouch request"""
_149
authy_id = request.json.get('authy_id')
_149
# When you're configuring your Endpoint/URL under OneTouch settings '1234'
_149
# is the preset 'authy_id'
_149
if authy_id != 1234:
_149
user = User.query.filter_by(authy_id=authy_id).one()
_149
_149
if not user:
_149
return ('', 404)
_149
_149
user.authy_status = request.json.get('status')
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
return ('', 200)
_149
_149
_149
@auth.route('/login/status')
_149
def login_status():
_149
"""
_149
Used by AJAX requests to check the OneTouch verification status of a user
_149
"""
_149
user = User.query.get(session['user_id'])
_149
return user.authy_status
_149
_149
_149
@auth.route('/verify', methods=['GET', 'POST'])
_149
@login_required
_149
def verify():
_149
"""Powers token validation (not using OneTouch)"""
_149
form = VerifyForm(request.form)
_149
user = User.query.get(session['user_id'])
_149
_149
# Send a token to our user when they GET this page
_149
if request.method == 'GET':
_149
send_authy_token_request(user.authy_id)
_149
_149
if form.validate_on_submit():
_149
user_entered_code = form.verification_code.data
_149
_149
verified = verify_authy_token(user.authy_id, str(user_entered_code))
_149
if verified.ok():
_149
user.authy_status = 'approved'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash(
_149
"You're logged in! Thanks for using two factor verification.", 'success'
_149
) # noqa: E501
_149
return redirect(url_for('main.account'))
_149
else:
_149
form.errors['verification_code'] = ['Code invalid - please try again.']
_149
_149
return render_template('verify.html', form=form)
_149
_149
_149
@auth.route('/resend', methods=['POST'])
_149
@login_required
_149
def resend():
_149
"""Resends a verification token to a user"""
_149
user = User.query.get(session.get('user_id'))
_149
send_authy_token_request(user.authy_id)
_149
flash('I just re-sent your verification code - enter it below.', 'info')
_149
return redirect(url_for('auth.verify'))
_149
_149
_149
@auth.route('/logout')
_149
def log_out():
_149
"""Log out a user, clearing their session variables"""
_149
user_id = session.pop('user_id', None)
_149
user = User.query.get(user_id)
_149
user.authy_status = 'unverified'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash("You're now logged out! Thanks for visiting.", 'info')
_149
return redirect(url_for('main.home'))


Send the OneTouch Request

send-the-onetouch-request page anchor

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:


_10
data = {
_10
'api_key': client.api_key,
_10
'message': "Request to send money to Jarod's vault",
_10
'details[Request From]': 'Jarod',
_10
'details[Amount Requested]': '1,000,000',
_10
'details[Currency]': 'Galleons'
_10
}

twofa/models.py


_62
from werkzeug.security import generate_password_hash, check_password_hash
_62
_62
from . import db
_62
from .utils import authy_user_has_app, send_authy_one_touch_request
_62
_62
_62
class User(db.Model):
_62
"""
_62
Represents a single user in the system.
_62
"""
_62
_62
__tablename__ = 'users'
_62
_62
AUTHY_STATUSES = ('unverified', 'onetouch', 'sms', 'token', 'approved', 'denied')
_62
_62
id = db.Column(db.Integer, primary_key=True)
_62
email = db.Column(db.String(64), unique=True, index=True)
_62
password_hash = db.Column(db.String(128))
_62
full_name = db.Column(db.String(256))
_62
country_code = db.Column(db.Integer)
_62
phone = db.Column(db.String(30))
_62
authy_id = db.Column(db.Integer)
_62
authy_status = db.Column(db.Enum(*AUTHY_STATUSES, name='authy_statuses'))
_62
_62
def __init__(
_62
self,
_62
email,
_62
password,
_62
full_name,
_62
country_code,
_62
phone,
_62
authy_id,
_62
authy_status='approved',
_62
):
_62
self.email = email
_62
self.password = password
_62
self.full_name = full_name
_62
self.country_code = country_code
_62
self.phone = phone
_62
self.authy_id = authy_id
_62
self.authy_status = authy_status
_62
_62
def __repr__(self):
_62
return '<User %r>' % self.email
_62
_62
@property
_62
def password(self):
_62
raise AttributeError('password is not readable')
_62
_62
@property
_62
def has_authy_app(self):
_62
return authy_user_has_app(self.authy_id)
_62
_62
@password.setter
_62
def password(self, password):
_62
self.password_hash = generate_password_hash(password)
_62
_62
def verify_password(self, password):
_62
return check_password_hash(self.password_hash, password)
_62
_62
def send_one_touch_request(self):
_62
return send_authy_one_touch_request(self.authy_id, self.email)

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

configure-the-onetouch-callback page anchor

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.

Note: In order to verify that the request is coming from Authy we've written a decorator, @verify_authy_request,(link takes you to an external page) 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.

Update user status using Authy Callback

update-user-status-using-authy-callback page anchor

twofa/auth/views.py


_149
from authy import AuthyApiException
_149
from flask import flash, jsonify, redirect, render_template, request, session, url_for
_149
_149
from . import auth
_149
from .forms import LoginForm, SignUpForm, VerifyForm
_149
from ..database import db
_149
from ..decorators import login_required, verify_authy_request
_149
from ..models import User
_149
from ..utils import create_user, send_authy_token_request, verify_authy_token
_149
_149
_149
@auth.route('/sign-up', methods=['GET', 'POST'])
_149
def sign_up():
_149
"""Powers the new user form"""
_149
form = SignUpForm(request.form)
_149
_149
if form.validate_on_submit():
_149
try:
_149
user = create_user(form)
_149
session['user_id'] = user.id
_149
_149
return redirect(url_for('main.account'))
_149
_149
except AuthyApiException as e:
_149
form.errors['Authy API'] = [
_149
'There was an error creating the Authy user',
_149
e.msg,
_149
]
_149
_149
return render_template('signup.html', form=form)
_149
_149
_149
@auth.route('/login', methods=['GET', 'POST'])
_149
def log_in():
_149
"""
_149
Powers the main login form.
_149
_149
- GET requests render the username / password form
_149
- POST requests process the form data via an AJAX request triggered in the
_149
user's browser
_149
"""
_149
form = LoginForm(request.form)
_149
_149
if form.validate_on_submit():
_149
user = User.query.filter_by(email=form.email.data).first()
_149
if user is not None and user.verify_password(form.password.data):
_149
session['user_id'] = user.id
_149
_149
if user.has_authy_app:
_149
# Send a request to verify this user's login with OneTouch
_149
one_touch_response = user.send_one_touch_request()
_149
return jsonify(one_touch_response)
_149
else:
_149
return jsonify({'success': False})
_149
else:
_149
# The username and password weren't valid
_149
form.email.errors.append(
_149
'The username and password combination you entered are invalid'
_149
)
_149
_149
if request.method == 'POST':
_149
# This was an AJAX request, and we should return any errors as JSON
_149
return jsonify(
_149
{'error': render_template('_login_error.html', form=form)}
_149
) # noqa: E501
_149
else:
_149
return render_template('login.html', form=form)
_149
_149
_149
@auth.route('/authy/callback', methods=['POST'])
_149
@verify_authy_request
_149
def authy_callback():
_149
"""Authy uses this endpoint to tell us the result of a OneTouch request"""
_149
authy_id = request.json.get('authy_id')
_149
# When you're configuring your Endpoint/URL under OneTouch settings '1234'
_149
# is the preset 'authy_id'
_149
if authy_id != 1234:
_149
user = User.query.filter_by(authy_id=authy_id).one()
_149
_149
if not user:
_149
return ('', 404)
_149
_149
user.authy_status = request.json.get('status')
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
return ('', 200)
_149
_149
_149
@auth.route('/login/status')
_149
def login_status():
_149
"""
_149
Used by AJAX requests to check the OneTouch verification status of a user
_149
"""
_149
user = User.query.get(session['user_id'])
_149
return user.authy_status
_149
_149
_149
@auth.route('/verify', methods=['GET', 'POST'])
_149
@login_required
_149
def verify():
_149
"""Powers token validation (not using OneTouch)"""
_149
form = VerifyForm(request.form)
_149
user = User.query.get(session['user_id'])
_149
_149
# Send a token to our user when they GET this page
_149
if request.method == 'GET':
_149
send_authy_token_request(user.authy_id)
_149
_149
if form.validate_on_submit():
_149
user_entered_code = form.verification_code.data
_149
_149
verified = verify_authy_token(user.authy_id, str(user_entered_code))
_149
if verified.ok():
_149
user.authy_status = 'approved'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash(
_149
"You're logged in! Thanks for using two factor verification.", 'success'
_149
) # noqa: E501
_149
return redirect(url_for('main.account'))
_149
else:
_149
form.errors['verification_code'] = ['Code invalid - please try again.']
_149
_149
return render_template('verify.html', form=form)
_149
_149
_149
@auth.route('/resend', methods=['POST'])
_149
@login_required
_149
def resend():
_149
"""Resends a verification token to a user"""
_149
user = User.query.get(session.get('user_id'))
_149
send_authy_token_request(user.authy_id)
_149
flash('I just re-sent your verification code - enter it below.', 'info')
_149
return redirect(url_for('auth.verify'))
_149
_149
_149
@auth.route('/logout')
_149
def log_out():
_149
"""Log out a user, clearing their session variables"""
_149
user_id = session.pop('user_id', None)
_149
user = User.query.get(user_id)
_149
user.authy_status = 'unverified'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash("You're now logged out! Thanks for visiting.", 'info')
_149
return redirect(url_for('main.home'))

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


Disabling Unsuccessful Callbacks

disabling-unsuccessful-callbacks page anchor

Scenario: The OneTouch callback URL provided by you is no longer active.

Action: We will disable the OneTouch callback after 3 consecutive HTTP error responses. We will also

  • Set the OneTouch callback URL to blank.
  • Send an email notifying you that the OneTouch callback is disabled with details on how to enable the OneTouch callback.

How to enable OneTouch callback? You need to update the OneTouch callback endpoint, which will allow the OneTouch callback.

Visit the Twilio Console: Console > Authy > Applications > {ApplicationName} > Push Authentication > Webhooks > Endpoint/URL to update the Endpoint/URL with a valid OneTouch callback URL.


Handle Two-Factor Asynchronously

handle-two-factor-asynchronously page anchor

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.

Handle Two-Factor Asynchronously

handle-two-factor-asynchronously-1 page anchor

twofa/static/js/sessions.js


_44
$(document).ready(function() {
_44
_44
$('#login-form').submit(function(e) {
_44
e.preventDefault();
_44
const formData = $(e.currentTarget).serialize();
_44
attemptOneTouchVerification(formData);
_44
});
_44
_44
const attemptOneTouchVerification = function(form) {
_44
$.post( "/login", form, function(data) {
_44
$('.form-errors').remove();
_44
// Check first if we successfully authenticated the username and password
_44
if (data.hasOwnProperty('error')) {
_44
$('#login-form').prepend(data.error);
_44
return;
_44
}
_44
_44
if (data.success) {
_44
$('#authy-modal').modal({backdrop:'static'},'show');
_44
$('.auth-ot').fadeIn();
_44
checkForOneTouch();
_44
} else {
_44
redirectToTokenForm();
_44
}
_44
});
_44
};
_44
_44
const checkForOneTouch = function() {
_44
$.get( "/login/status", function(data) {
_44
_44
if (data === 'approved') {
_44
window.location.href = "/account";
_44
} else if (data === 'denied') {
_44
redirectToTokenForm();
_44
} else {
_44
setTimeout(checkForOneTouch, 2000);
_44
}
_44
});
_44
};
_44
_44
const redirectToTokenForm = function() {
_44
window.location.href = "/verify";
_44
};
_44
});

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


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.

twofa/auth/views.py


_149
from authy import AuthyApiException
_149
from flask import flash, jsonify, redirect, render_template, request, session, url_for
_149
_149
from . import auth
_149
from .forms import LoginForm, SignUpForm, VerifyForm
_149
from ..database import db
_149
from ..decorators import login_required, verify_authy_request
_149
from ..models import User
_149
from ..utils import create_user, send_authy_token_request, verify_authy_token
_149
_149
_149
@auth.route('/sign-up', methods=['GET', 'POST'])
_149
def sign_up():
_149
"""Powers the new user form"""
_149
form = SignUpForm(request.form)
_149
_149
if form.validate_on_submit():
_149
try:
_149
user = create_user(form)
_149
session['user_id'] = user.id
_149
_149
return redirect(url_for('main.account'))
_149
_149
except AuthyApiException as e:
_149
form.errors['Authy API'] = [
_149
'There was an error creating the Authy user',
_149
e.msg,
_149
]
_149
_149
return render_template('signup.html', form=form)
_149
_149
_149
@auth.route('/login', methods=['GET', 'POST'])
_149
def log_in():
_149
"""
_149
Powers the main login form.
_149
_149
- GET requests render the username / password form
_149
- POST requests process the form data via an AJAX request triggered in the
_149
user's browser
_149
"""
_149
form = LoginForm(request.form)
_149
_149
if form.validate_on_submit():
_149
user = User.query.filter_by(email=form.email.data).first()
_149
if user is not None and user.verify_password(form.password.data):
_149
session['user_id'] = user.id
_149
_149
if user.has_authy_app:
_149
# Send a request to verify this user's login with OneTouch
_149
one_touch_response = user.send_one_touch_request()
_149
return jsonify(one_touch_response)
_149
else:
_149
return jsonify({'success': False})
_149
else:
_149
# The username and password weren't valid
_149
form.email.errors.append(
_149
'The username and password combination you entered are invalid'
_149
)
_149
_149
if request.method == 'POST':
_149
# This was an AJAX request, and we should return any errors as JSON
_149
return jsonify(
_149
{'error': render_template('_login_error.html', form=form)}
_149
) # noqa: E501
_149
else:
_149
return render_template('login.html', form=form)
_149
_149
_149
@auth.route('/authy/callback', methods=['POST'])
_149
@verify_authy_request
_149
def authy_callback():
_149
"""Authy uses this endpoint to tell us the result of a OneTouch request"""
_149
authy_id = request.json.get('authy_id')
_149
# When you're configuring your Endpoint/URL under OneTouch settings '1234'
_149
# is the preset 'authy_id'
_149
if authy_id != 1234:
_149
user = User.query.filter_by(authy_id=authy_id).one()
_149
_149
if not user:
_149
return ('', 404)
_149
_149
user.authy_status = request.json.get('status')
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
return ('', 200)
_149
_149
_149
@auth.route('/login/status')
_149
def login_status():
_149
"""
_149
Used by AJAX requests to check the OneTouch verification status of a user
_149
"""
_149
user = User.query.get(session['user_id'])
_149
return user.authy_status
_149
_149
_149
@auth.route('/verify', methods=['GET', 'POST'])
_149
@login_required
_149
def verify():
_149
"""Powers token validation (not using OneTouch)"""
_149
form = VerifyForm(request.form)
_149
user = User.query.get(session['user_id'])
_149
_149
# Send a token to our user when they GET this page
_149
if request.method == 'GET':
_149
send_authy_token_request(user.authy_id)
_149
_149
if form.validate_on_submit():
_149
user_entered_code = form.verification_code.data
_149
_149
verified = verify_authy_token(user.authy_id, str(user_entered_code))
_149
if verified.ok():
_149
user.authy_status = 'approved'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash(
_149
"You're logged in! Thanks for using two factor verification.", 'success'
_149
) # noqa: E501
_149
return redirect(url_for('main.account'))
_149
else:
_149
form.errors['verification_code'] = ['Code invalid - please try again.']
_149
_149
return render_template('verify.html', form=form)
_149
_149
_149
@auth.route('/resend', methods=['POST'])
_149
@login_required
_149
def resend():
_149
"""Resends a verification token to a user"""
_149
user = User.query.get(session.get('user_id'))
_149
send_authy_token_request(user.authy_id)
_149
flash('I just re-sent your verification code - enter it below.', 'info')
_149
return redirect(url_for('auth.verify'))
_149
_149
_149
@auth.route('/logout')
_149
def log_out():
_149
"""Log out a user, clearing their session variables"""
_149
user_id = session.pop('user_id', None)
_149
user = User.query.get(user_id)
_149
user.authy_status = 'unverified'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash("You're now logged out! Thanks for visiting.", 'info')
_149
return redirect(url_for('main.home'))

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


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.

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.

Verify users via Authy Token

verify-users-via-authy-token page anchor

twofa/auth/views.py


_149
from authy import AuthyApiException
_149
from flask import flash, jsonify, redirect, render_template, request, session, url_for
_149
_149
from . import auth
_149
from .forms import LoginForm, SignUpForm, VerifyForm
_149
from ..database import db
_149
from ..decorators import login_required, verify_authy_request
_149
from ..models import User
_149
from ..utils import create_user, send_authy_token_request, verify_authy_token
_149
_149
_149
@auth.route('/sign-up', methods=['GET', 'POST'])
_149
def sign_up():
_149
"""Powers the new user form"""
_149
form = SignUpForm(request.form)
_149
_149
if form.validate_on_submit():
_149
try:
_149
user = create_user(form)
_149
session['user_id'] = user.id
_149
_149
return redirect(url_for('main.account'))
_149
_149
except AuthyApiException as e:
_149
form.errors['Authy API'] = [
_149
'There was an error creating the Authy user',
_149
e.msg,
_149
]
_149
_149
return render_template('signup.html', form=form)
_149
_149
_149
@auth.route('/login', methods=['GET', 'POST'])
_149
def log_in():
_149
"""
_149
Powers the main login form.
_149
_149
- GET requests render the username / password form
_149
- POST requests process the form data via an AJAX request triggered in the
_149
user's browser
_149
"""
_149
form = LoginForm(request.form)
_149
_149
if form.validate_on_submit():
_149
user = User.query.filter_by(email=form.email.data).first()
_149
if user is not None and user.verify_password(form.password.data):
_149
session['user_id'] = user.id
_149
_149
if user.has_authy_app:
_149
# Send a request to verify this user's login with OneTouch
_149
one_touch_response = user.send_one_touch_request()
_149
return jsonify(one_touch_response)
_149
else:
_149
return jsonify({'success': False})
_149
else:
_149
# The username and password weren't valid
_149
form.email.errors.append(
_149
'The username and password combination you entered are invalid'
_149
)
_149
_149
if request.method == 'POST':
_149
# This was an AJAX request, and we should return any errors as JSON
_149
return jsonify(
_149
{'error': render_template('_login_error.html', form=form)}
_149
) # noqa: E501
_149
else:
_149
return render_template('login.html', form=form)
_149
_149
_149
@auth.route('/authy/callback', methods=['POST'])
_149
@verify_authy_request
_149
def authy_callback():
_149
"""Authy uses this endpoint to tell us the result of a OneTouch request"""
_149
authy_id = request.json.get('authy_id')
_149
# When you're configuring your Endpoint/URL under OneTouch settings '1234'
_149
# is the preset 'authy_id'
_149
if authy_id != 1234:
_149
user = User.query.filter_by(authy_id=authy_id).one()
_149
_149
if not user:
_149
return ('', 404)
_149
_149
user.authy_status = request.json.get('status')
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
return ('', 200)
_149
_149
_149
@auth.route('/login/status')
_149
def login_status():
_149
"""
_149
Used by AJAX requests to check the OneTouch verification status of a user
_149
"""
_149
user = User.query.get(session['user_id'])
_149
return user.authy_status
_149
_149
_149
@auth.route('/verify', methods=['GET', 'POST'])
_149
@login_required
_149
def verify():
_149
"""Powers token validation (not using OneTouch)"""
_149
form = VerifyForm(request.form)
_149
user = User.query.get(session['user_id'])
_149
_149
# Send a token to our user when they GET this page
_149
if request.method == 'GET':
_149
send_authy_token_request(user.authy_id)
_149
_149
if form.validate_on_submit():
_149
user_entered_code = form.verification_code.data
_149
_149
verified = verify_authy_token(user.authy_id, str(user_entered_code))
_149
if verified.ok():
_149
user.authy_status = 'approved'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash(
_149
"You're logged in! Thanks for using two factor verification.", 'success'
_149
) # noqa: E501
_149
return redirect(url_for('main.account'))
_149
else:
_149
form.errors['verification_code'] = ['Code invalid - please try again.']
_149
_149
return render_template('verify.html', form=form)
_149
_149
_149
@auth.route('/resend', methods=['POST'])
_149
@login_required
_149
def resend():
_149
"""Resends a verification token to a user"""
_149
user = User.query.get(session.get('user_id'))
_149
send_authy_token_request(user.authy_id)
_149
flash('I just re-sent your verification code - enter it below.', 'info')
_149
return redirect(url_for('auth.verify'))
_149
_149
_149
@auth.route('/logout')
_149
def log_out():
_149
"""Log out a user, clearing their session variables"""
_149
user_id = session.pop('user_id', None)
_149
user = User.query.get(user_id)
_149
user.authy_status = 'unverified'
_149
db.session.add(user)
_149
db.session.commit()
_149
_149
flash("You're now logged out! Thanks for visiting.", 'info')
_149
return redirect(url_for('main.home'))

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


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

SMS and MMS Notifications

Faster than email 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?

did-this-help page anchor

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(link takes you to an external page) and let us know what you build!


Rate this page: