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.
This Express.js sample application demonstrates how to build a login system that uses two factors of authentication to log in users. Head to the application's README.md to see how to run the application locally.
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 first logging the user into the app, and then validating their mobile device.
For the second factor, we will validate that the user has their mobile phone by either:
See how VMware uses Authy 2FA to secure their enterprise mobility management solution.
If you haven't done so 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:
Once we have an Authy API key, we store it in this initializer file.
config.js
1module.exports = {2// HTTP port3port: process.env.PORT || 3000,45// Production Authy API key6authyApiKey: process.env.AUTHY_API_KEY,78// MongoDB connection string - MONGO_URL is for local dev,9// MONGOLAB_URI is for the MongoLab add-on for Heroku deployment10mongoUrl: process.env.MONGOLAB_URI || process.env.MONGO_URL11};
Now that we've configured our Express app, let's take a look at how we register a user with Authy.
When a new user is created we also register the user with Authy.
All Authy needs to get a user set up for your application is that user's email, phone number and country code. We need to make sure this information is required when the user signs up.
Once we register the User with Authy we get an id
back that we will store as the user's authyId
. This is very important since it's how we will verify the identity of our user with Authy.
models/User.js
1var mongoose = require('mongoose');2var bcrypt = require('bcrypt');3var config = require('../config');4var onetouch = require('../api/onetouch');56// Create authenticated Authy API client7var authy = require('authy')(config.authyApiKey);89// Used to generate password hash10var SALT_WORK_FACTOR = 10;1112// Define user model schema13var UserSchema = new mongoose.Schema({14fullName: {15type: String,16required: true17},18countryCode: {19type: String,20required: true21},22phone: {23type: String,24required: true25},26authyId: String,27email: {28type: String,29required: true,30unique: true31},32password: {33type: String,34required: true35},36authyStatus: {37type: String,38default: 'unverified'39}40});4142// Middleware executed before save - hash the user's password43UserSchema.pre('save', function(next) {44var self = this;4546// only hash the password if it has been modified (or is new)47if (!self.isModified('password')) return next();4849// generate a salt50bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {51if (err) return next(err);5253// hash the password using our new salt54bcrypt.hash(self.password, salt, function(err, hash) {55if (err) return next(err);5657// override the cleartext password with the hashed one58self.password = hash;59next();60});61});6263if (!self.authyId) {64// Register this user if it's a new user65authy.register_user(self.email, self.phone, self.countryCode,66function(err, response) {67if(err){68if(response && response.json) {69response.json(err);70} else {71console.error(err);72}73return;74}75self.authyId = response.user.id;76self.save(function(err, doc) {77if (err || !doc) return next(err);78self = doc;79});80});81};82});8384// Test candidate password85UserSchema.methods.comparePassword = function(candidatePassword, cb) {86var self = this;87bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {88if (err) return cb(err);89cb(null, isMatch);90});91};9293// Send a OneTouch request to this user94UserSchema.methods.sendOneTouch = function(cb) {95var self = this;96self.authyStatus = 'unverified';97self.save();9899onetouch.send_approval_request(self.authyId, {100message: 'Request to Login to Twilio demo app',101email: self.email102}, function(err, authyres){103if (err && err.success != undefined) {104authyres = err;105err = null;106}107cb.call(self, err, authyres);108});109};110111// Send a 2FA token to this user112UserSchema.methods.sendAuthyToken = function(cb) {113var self = this;114115authy.request_sms(self.authyId, function(err, response) {116cb.call(self, err);117});118};119120// Test a 2FA token121UserSchema.methods.verifyAuthyToken = function(otp, cb) {122var self = this;123authy.verify(self.authyId, otp, function(err, response) {124cb.call(self, err, response);125});126};127128// Export user model129module.exports = mongoose.model('User', UserSchema);130
When a user attempts to log in to our website, a second form of identification is needed. Let's take a look at Authy's OneTouch verification first.
OneTouch works like so:
success
message backPOST
request to our app with an 'Approved' statusapi/sessions.js
1var Session = require('../models/Session');2var User = require('../models/User');3var error = require('./response_utils').error;4var ok = require('./response_utils').ok;56// Create a new session, first testing username/password combo7exports.create = function(request, response) {8var email = request.body.email;9var candidatePassword = request.body.password;1011// Look for a user by the given username12User.findOne({13email: email14}, function(err, user) {15if (err || !user) return invalid();1617// We have a user for that username, test password18user.comparePassword(candidatePassword, function(err, match) {19if (err || !match) return invalid();20return valid(user);21});22});2324// respond with a 403 for a login error25function invalid() {26error(response, 403, 'Invalid username/password combination.');27}2829// respond with a new session for a valid password, and send a 2FA token30function valid(user) {31Session.createSessionForUser(user, false, function(err, sess, authyResponse) {32if (err || !sess) {33error(response, 500,34'Error creating session - please log in again.');35} else {36// Send the unique token for this session and the onetouch response37response.send({38token: sess.token,39authyResponse: authyResponse40});41}42});43}44};4546// Destroy the given session (log out)47exports.destroy = function(request, response) {48request.session && request.session.remove(function(err, doc) {49if (err) {50error(response, 500, 'There was a problem logging you out - please retry.');51} else {52ok(response);53}54});55};5657// Public webhook for Authy to POST to58exports.authyCallback = function(request, response) {59var authyId = request.body.authy_id;6061// Respond with a 404 for a no user found error62function invalid() {63error(response,64404,65'No user found.'66);67}6869// Look for a user with the authy_id supplies70User.findOne({71authyId: authyId72}, function(err, user) {73if (err || !user) return invalid();74user.authyStatus = request.body.status;75user.save();76});77response.end();78};7980// Internal endpoint for checking the status of OneTouch81exports.authyStatus = function(request, response) {82var status = (request.user) ? request.user.authyStatus : 'unverified';83if (status == 'approved') {84request.session.confirmed = true;85request.session.save(function(err) {86if (err) return error(response, 500,87'There was an error validating your session.');88});89}90if (!request.session) {91return error(response, 404, 'No valid session found for this user.');92} else {93response.send({ status: status });94}95};9697// Validate a 2FA token98exports.verify = function(request, response) {99var oneTimeCode = request.body.code;100101if (!request.session || !request.user) {102return error(response, 404, 'No valid session found for this token.');103}104105// verify entered authy code106request.user.verifyAuthyToken(oneTimeCode, function(err) {107if (err) return error(response, 401, 'Invalid confirmation code.');108109// otherwise we're good! Validate the session110request.session.confirmed = true;111request.session.save(function(err) {112if (err) return error(response, 500,113'There was an error validating your session.');114115response.send({116token: request.session.token117});118});119});120};121122// Resend validation code123exports.resend = function(request, response) {124if (!request.user) return error(response, 404,125'No user found for this session, please log in again.');126127// Otherwise resend the code128request.user.sendAuthyToken(function(err) {129if (!request.user) return error(response, 500,130'No user found for this session, please log in again.');131132ok(response);133});134};
When our user logs in we immediately attempt to verify their identity with OneTouch. We will fallback gracefully if they don't have a OneTouch device, but we don't know until we try.
Authy lets us pass details with our OneTouch request. These can be messages, logos, and any other details we want to send. We could send any number of details by appending details['some_detail']
. You could imagine a scenario where we send a OneTouch request to approve a money transfer:
1details = {2message: "Request to send money to Jarod's vault",3from: "Jarod",4amount: "1,000,000",5currency: "Galleons"6}7
models/User.js
1var mongoose = require('mongoose');2var bcrypt = require('bcrypt');3var config = require('../config');4var onetouch = require('../api/onetouch');56// Create authenticated Authy API client7var authy = require('authy')(config.authyApiKey);89// Used to generate password hash10var SALT_WORK_FACTOR = 10;1112// Define user model schema13var UserSchema = new mongoose.Schema({14fullName: {15type: String,16required: true17},18countryCode: {19type: String,20required: true21},22phone: {23type: String,24required: true25},26authyId: String,27email: {28type: String,29required: true,30unique: true31},32password: {33type: String,34required: true35},36authyStatus: {37type: String,38default: 'unverified'39}40});4142// Middleware executed before save - hash the user's password43UserSchema.pre('save', function(next) {44var self = this;4546// only hash the password if it has been modified (or is new)47if (!self.isModified('password')) return next();4849// generate a salt50bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {51if (err) return next(err);5253// hash the password using our new salt54bcrypt.hash(self.password, salt, function(err, hash) {55if (err) return next(err);5657// override the cleartext password with the hashed one58self.password = hash;59next();60});61});6263if (!self.authyId) {64// Register this user if it's a new user65authy.register_user(self.email, self.phone, self.countryCode,66function(err, response) {67if(err){68if(response && response.json) {69response.json(err);70} else {71console.error(err);72}73return;74}75self.authyId = response.user.id;76self.save(function(err, doc) {77if (err || !doc) return next(err);78self = doc;79});80});81};82});8384// Test candidate password85UserSchema.methods.comparePassword = function(candidatePassword, cb) {86var self = this;87bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {88if (err) return cb(err);89cb(null, isMatch);90});91};9293// Send a OneTouch request to this user94UserSchema.methods.sendOneTouch = function(cb) {95var self = this;96self.authyStatus = 'unverified';97self.save();9899onetouch.send_approval_request(self.authyId, {100message: 'Request to Login to Twilio demo app',101email: self.email102}, function(err, authyres){103if (err && err.success != undefined) {104authyres = err;105err = null;106}107cb.call(self, err, authyres);108});109};110111// Send a 2FA token to this user112UserSchema.methods.sendAuthyToken = function(cb) {113var self = this;114115authy.request_sms(self.authyId, function(err, response) {116cb.call(self, err);117});118};119120// Test a 2FA token121UserSchema.methods.verifyAuthyToken = function(otp, cb) {122var self = this;123authy.verify(self.authyId, otp, function(err, response) {124cb.call(self, err, response);125});126};127128// Export user model129module.exports = mongoose.model('User', UserSchema);130
Note: We need some way to check the status of the user's two-factor process. In this case, we do so by updating the User.authyStatus
attribute. It's important we reset this before we log the user in.
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.
api/sessions.js
1var Session = require('../models/Session');2var User = require('../models/User');3var error = require('./response_utils').error;4var ok = require('./response_utils').ok;56// Create a new session, first testing username/password combo7exports.create = function(request, response) {8var email = request.body.email;9var candidatePassword = request.body.password;1011// Look for a user by the given username12User.findOne({13email: email14}, function(err, user) {15if (err || !user) return invalid();1617// We have a user for that username, test password18user.comparePassword(candidatePassword, function(err, match) {19if (err || !match) return invalid();20return valid(user);21});22});2324// respond with a 403 for a login error25function invalid() {26error(response, 403, 'Invalid username/password combination.');27}2829// respond with a new session for a valid password, and send a 2FA token30function valid(user) {31Session.createSessionForUser(user, false, function(err, sess, authyResponse) {32if (err || !sess) {33error(response, 500,34'Error creating session - please log in again.');35} else {36// Send the unique token for this session and the onetouch response37response.send({38token: sess.token,39authyResponse: authyResponse40});41}42});43}44};4546// Destroy the given session (log out)47exports.destroy = function(request, response) {48request.session && request.session.remove(function(err, doc) {49if (err) {50error(response, 500, 'There was a problem logging you out - please retry.');51} else {52ok(response);53}54});55};5657// Public webhook for Authy to POST to58exports.authyCallback = function(request, response) {59var authyId = request.body.authy_id;6061// Respond with a 404 for a no user found error62function invalid() {63error(response,64404,65'No user found.'66);67}6869// Look for a user with the authy_id supplies70User.findOne({71authyId: authyId72}, function(err, user) {73if (err || !user) return invalid();74user.authyStatus = request.body.status;75user.save();76});77response.end();78};7980// Internal endpoint for checking the status of OneTouch81exports.authyStatus = function(request, response) {82var status = (request.user) ? request.user.authyStatus : 'unverified';83if (status == 'approved') {84request.session.confirmed = true;85request.session.save(function(err) {86if (err) return error(response, 500,87'There was an error validating your session.');88});89}90if (!request.session) {91return error(response, 404, 'No valid session found for this user.');92} else {93response.send({ status: status });94}95};9697// Validate a 2FA token98exports.verify = function(request, response) {99var oneTimeCode = request.body.code;100101if (!request.session || !request.user) {102return error(response, 404, 'No valid session found for this token.');103}104105// verify entered authy code106request.user.verifyAuthyToken(oneTimeCode, function(err) {107if (err) return error(response, 401, 'Invalid confirmation code.');108109// otherwise we're good! Validate the session110request.session.confirmed = true;111request.session.save(function(err) {112if (err) return error(response, 500,113'There was an error validating your session.');114115response.send({116token: request.session.token117});118});119});120};121122// Resend validation code123exports.resend = function(request, response) {124if (!request.user) return error(response, 404,125'No user found for this session, please log in again.');126127// Otherwise resend the code128request.user.sendAuthyToken(function(err) {129if (!request.user) return error(response, 500,130'No user found for this session, please log in again.');131132ok(response);133});134};
Here in our callback, we look up the user using the authy_id
sent with the Authy POST
request. At this point we would ideally use a websocket to let our client know that we received a response from Authy. However, for this version we're going to just update the authyStatus
on the user. Now all our client-side code needs to do is check for user.authyStatus.approved
before logging in the user.
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
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.
Our user interface for this example is a single page application written using Backbone and jQuery.
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 submitted and pass the data to our /session
controller using Ajax. Depending on how that endpoint responds we will either ask the user for a token or await their OneTouch response.
If we expect a OneTouch response, we will begin polling /authy/status
until we see that the OneTouch login was either approved or denied. Take a look at this controller and see what is happening.
public/app/views/Login.js
1(function() {2app.views.LoginView = app.views.BaseView.extend({3// name of the template file to load from the server4templateName: 'login',56// UI events7events: {8'submit #loginForm': 'login'9},1011initialize: function() {12var self = this;13// default behavior, render page into #page section14app.router.on('route:login', function() {15self.render();16});17},1819// Hit login service20login: function(e) {21var self = this;2223e.preventDefault();24app.set('message', null);25$.ajax('/session', {26method: 'POST',27data: {28email: self.$('#email').val(),29password: self.$('#password').val()30}31}).done(function(data) {32// If session returns oneTouch status.success wait for oneStatus approval33app.set('token', data.token);34if (data.authyResponse.success) {35app.set('onetouch', true);36app.set('message', {37error: false,38message: 'Awaiting One Touch approval.'39});40self.checkOneTouchStatus();41} else {42app.router.navigate('verify', {43trigger: true44});45}46}).fail(function(err) {47app.set('message', {48error: true,49message: err.responseJSON.message ||50'Sorry, an error occurred, please log in again.'51});52});53},5455checkOneTouchStatus: function() {56var self = this;57$.ajax('/authy/status', {58method: 'GET',59headers: {60'X-API-TOKEN': app.get('token')61}62}).done(function(data) {63if (data.status == 'approved') {64app.router.navigate('user', {65trigger: true66});67} else if (data.status == 'denied') {68app.router.navigate('verify', {69trigger: true70});71app.set('message', {72error: true,73message: 'OneTouch Login request denied.'74});75} else {76setTimeout(self.checkOneTouchStatus(), 3000);77}78});79}80});81})();
Here is the endpoint that our JavaScript is polling. It is waiting for the user status to be either 'Approved' or 'Denied'. If the user has approved the OneTouch request, we will save their session as confirmed
, which officially logs them in.
If the request was denied we render the /verify
page and ask the user to log in with a Token.
api/sessions.js
1var Session = require('../models/Session');2var User = require('../models/User');3var error = require('./response_utils').error;4var ok = require('./response_utils').ok;56// Create a new session, first testing username/password combo7exports.create = function(request, response) {8var email = request.body.email;9var candidatePassword = request.body.password;1011// Look for a user by the given username12User.findOne({13email: email14}, function(err, user) {15if (err || !user) return invalid();1617// We have a user for that username, test password18user.comparePassword(candidatePassword, function(err, match) {19if (err || !match) return invalid();20return valid(user);21});22});2324// respond with a 403 for a login error25function invalid() {26error(response, 403, 'Invalid username/password combination.');27}2829// respond with a new session for a valid password, and send a 2FA token30function valid(user) {31Session.createSessionForUser(user, false, function(err, sess, authyResponse) {32if (err || !sess) {33error(response, 500,34'Error creating session - please log in again.');35} else {36// Send the unique token for this session and the onetouch response37response.send({38token: sess.token,39authyResponse: authyResponse40});41}42});43}44};4546// Destroy the given session (log out)47exports.destroy = function(request, response) {48request.session && request.session.remove(function(err, doc) {49if (err) {50error(response, 500, 'There was a problem logging you out - please retry.');51} else {52ok(response);53}54});55};5657// Public webhook for Authy to POST to58exports.authyCallback = function(request, response) {59var authyId = request.body.authy_id;6061// Respond with a 404 for a no user found error62function invalid() {63error(response,64404,65'No user found.'66);67}6869// Look for a user with the authy_id supplies70User.findOne({71authyId: authyId72}, function(err, user) {73if (err || !user) return invalid();74user.authyStatus = request.body.status;75user.save();76});77response.end();78};7980// Internal endpoint for checking the status of OneTouch81exports.authyStatus = function(request, response) {82var status = (request.user) ? request.user.authyStatus : 'unverified';83if (status == 'approved') {84request.session.confirmed = true;85request.session.save(function(err) {86if (err) return error(response, 500,87'There was an error validating your session.');88});89}90if (!request.session) {91return error(response, 404, 'No valid session found for this user.');92} else {93response.send({ status: status });94}95};9697// Validate a 2FA token98exports.verify = function(request, response) {99var oneTimeCode = request.body.code;100101if (!request.session || !request.user) {102return error(response, 404, 'No valid session found for this token.');103}104105// verify entered authy code106request.user.verifyAuthyToken(oneTimeCode, function(err) {107if (err) return error(response, 401, 'Invalid confirmation code.');108109// otherwise we're good! Validate the session110request.session.confirmed = true;111request.session.save(function(err) {112if (err) return error(response, 500,113'There was an error validating your session.');114115response.send({116token: request.session.token117});118});119});120};121122// Resend validation code123exports.resend = function(request, response) {124if (!request.user) return error(response, 404,125'No user found for this session, please log in again.');126127// Otherwise resend the code128request.user.sendAuthyToken(function(err) {129if (!request.user) return error(response, 500,130'No user found for this session, please log in again.');131132ok(response);133});134};
Now let's take a look at how we handle two-factor with tokens.
Once there is an Authy user ID associated with our user model, we can request that an SMS verification token be sent out to the user's phone. Authy supports token validation in their mobile app as well, so if our user has the app it will default to sending a push notification instead of an SMS.
If needed, we can call this method on the user instance multiple times. This is what happens every time the user clicks "Resend Code" on the web form.
models/User.js
1var mongoose = require('mongoose');2var bcrypt = require('bcrypt');3var config = require('../config');4var onetouch = require('../api/onetouch');56// Create authenticated Authy API client7var authy = require('authy')(config.authyApiKey);89// Used to generate password hash10var SALT_WORK_FACTOR = 10;1112// Define user model schema13var UserSchema = new mongoose.Schema({14fullName: {15type: String,16required: true17},18countryCode: {19type: String,20required: true21},22phone: {23type: String,24required: true25},26authyId: String,27email: {28type: String,29required: true,30unique: true31},32password: {33type: String,34required: true35},36authyStatus: {37type: String,38default: 'unverified'39}40});4142// Middleware executed before save - hash the user's password43UserSchema.pre('save', function(next) {44var self = this;4546// only hash the password if it has been modified (or is new)47if (!self.isModified('password')) return next();4849// generate a salt50bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {51if (err) return next(err);5253// hash the password using our new salt54bcrypt.hash(self.password, salt, function(err, hash) {55if (err) return next(err);5657// override the cleartext password with the hashed one58self.password = hash;59next();60});61});6263if (!self.authyId) {64// Register this user if it's a new user65authy.register_user(self.email, self.phone, self.countryCode,66function(err, response) {67if(err){68if(response && response.json) {69response.json(err);70} else {71console.error(err);72}73return;74}75self.authyId = response.user.id;76self.save(function(err, doc) {77if (err || !doc) return next(err);78self = doc;79});80});81};82});8384// Test candidate password85UserSchema.methods.comparePassword = function(candidatePassword, cb) {86var self = this;87bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {88if (err) return cb(err);89cb(null, isMatch);90});91};9293// Send a OneTouch request to this user94UserSchema.methods.sendOneTouch = function(cb) {95var self = this;96self.authyStatus = 'unverified';97self.save();9899onetouch.send_approval_request(self.authyId, {100message: 'Request to Login to Twilio demo app',101email: self.email102}, function(err, authyres){103if (err && err.success != undefined) {104authyres = err;105err = null;106}107cb.call(self, err, authyres);108});109};110111// Send a 2FA token to this user112UserSchema.methods.sendAuthyToken = function(cb) {113var self = this;114115authy.request_sms(self.authyId, function(err, response) {116cb.call(self, err);117});118};119120// Test a 2FA token121UserSchema.methods.verifyAuthyToken = function(otp, cb) {122var self = this;123authy.verify(self.authyId, otp, function(err, response) {124cb.call(self, err, response);125});126};127128// Export user model129module.exports = mongoose.model('User', UserSchema);130
Our Express route handler will grab the code submitted on the form in order to validate it. The connect middleware function executes before this handler and adds a user
property to the request
object that contains a Mongoose model instance representing the user associated with this session. We use verifyAuthyToken
on the User
model to check if the code submitted by the user is legit.
api/sessions.js
1var Session = require('../models/Session');2var User = require('../models/User');3var error = require('./response_utils').error;4var ok = require('./response_utils').ok;56// Create a new session, first testing username/password combo7exports.create = function(request, response) {8var email = request.body.email;9var candidatePassword = request.body.password;1011// Look for a user by the given username12User.findOne({13email: email14}, function(err, user) {15if (err || !user) return invalid();1617// We have a user for that username, test password18user.comparePassword(candidatePassword, function(err, match) {19if (err || !match) return invalid();20return valid(user);21});22});2324// respond with a 403 for a login error25function invalid() {26error(response, 403, 'Invalid username/password combination.');27}2829// respond with a new session for a valid password, and send a 2FA token30function valid(user) {31Session.createSessionForUser(user, false, function(err, sess, authyResponse) {32if (err || !sess) {33error(response, 500,34'Error creating session - please log in again.');35} else {36// Send the unique token for this session and the onetouch response37response.send({38token: sess.token,39authyResponse: authyResponse40});41}42});43}44};4546// Destroy the given session (log out)47exports.destroy = function(request, response) {48request.session && request.session.remove(function(err, doc) {49if (err) {50error(response, 500, 'There was a problem logging you out - please retry.');51} else {52ok(response);53}54});55};5657// Public webhook for Authy to POST to58exports.authyCallback = function(request, response) {59var authyId = request.body.authy_id;6061// Respond with a 404 for a no user found error62function invalid() {63error(response,64404,65'No user found.'66);67}6869// Look for a user with the authy_id supplies70User.findOne({71authyId: authyId72}, function(err, user) {73if (err || !user) return invalid();74user.authyStatus = request.body.status;75user.save();76});77response.end();78};7980// Internal endpoint for checking the status of OneTouch81exports.authyStatus = function(request, response) {82var status = (request.user) ? request.user.authyStatus : 'unverified';83if (status == 'approved') {84request.session.confirmed = true;85request.session.save(function(err) {86if (err) return error(response, 500,87'There was an error validating your session.');88});89}90if (!request.session) {91return error(response, 404, 'No valid session found for this user.');92} else {93response.send({ status: status });94}95};9697// Validate a 2FA token98exports.verify = function(request, response) {99var oneTimeCode = request.body.code;100101if (!request.session || !request.user) {102return error(response, 404, 'No valid session found for this token.');103}104105// verify entered authy code106request.user.verifyAuthyToken(oneTimeCode, function(err) {107if (err) return error(response, 401, 'Invalid confirmation code.');108109// otherwise we're good! Validate the session110request.session.confirmed = true;111request.session.save(function(err) {112if (err) return error(response, 500,113'There was an error validating your session.');114115response.send({116token: request.session.token117});118});119});120};121122// Resend validation code123exports.resend = function(request, response) {124if (!request.user) return error(response, 404,125'No user found for this session, please log in again.');126127// Otherwise resend the code128request.user.sendAuthyToken(function(err) {129if (!request.user) return error(response, 500,130'No user found for this session, please log in again.');131132ok(response);133});134};
That's it! We've just implemented two-factor authentication using three different methods and the latest in Authy technology.
If you're a Node.js developer working with Twilio, you might want to check out these other tutorials.
Increase the security of your login system by verifying a user's mobile phone.
Faster than email and less likely to get blocked, text messages are great for timed alerts and notifications. Learn how to send out SMS (and MMS) notifications to a list of server administrators.