# Two-Factor Authentication with Authy, Node.js and Express

> \[!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](/docs/verify/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](https://www.twilio.com/blog/migrate-authy-to-verify).

This [Express.js](https://expressjs.com/) 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](https://github.com/TwilioDevEd/authy2fa-node) 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](https://en.wikipedia.org/wiki/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:

* Sending them a OneTouch push notification to their mobile Authy app
* Sending them a token through their mobile Authy app
* Sending them a one-time token in a text message [sent with Authy via Twilio](https://www.authy.com/).

*[See how VMware uses Authy 2FA to secure their enterprise mobility management solution.](https://customers.twilio.com/1143/vmware/?utm_source=docs\&utm_campaign=docs_to_stories)*

## Configuring Authy

If you haven't done so already, now is the time to [sign up for Authy](https://dashboard.authy.com/signup). Create your first application, naming it whatever you wish. After you create your application, your production API key will be visible on your [dashboard](https://dashboard.authy.com):

Once we have an Authy API key, we store it in this initializer file.

```js title="Authy configuration" description="config.js"
module.exports = {
    // HTTP port
    port: process.env.PORT || 3000,

    // Production Authy API key
    authyApiKey: process.env.AUTHY_API_KEY,

    // MongoDB connection string - MONGO_URL is for local dev,
    // MONGOLAB_URI is for the MongoLab add-on for Heroku deployment
    mongoUrl: process.env.MONGOLAB_URI || process.env.MONGO_URL
};
```

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

## 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.

```js title="Register a User with Authy" description="models/User.js"
// !mark(64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79)
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var config = require('../config');
var onetouch = require('../api/onetouch');

// Create authenticated Authy API client
var authy = require('authy')(config.authyApiKey);

// Used to generate password hash
var SALT_WORK_FACTOR = 10;

// Define user model schema
var UserSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required: true
    },
    countryCode: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    authyId: String,
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    authyStatus: {
        type: String,
        default: 'unverified'
    }
});

// Middleware executed before save - hash the user's password
UserSchema.pre('save', function(next) {
    var self = this;

    // only hash the password if it has been modified (or is new)
    if (!self.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(self.password, salt, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            self.password = hash;
            next();
        });
    });

    if (!self.authyId) {
        // Register this user if it's a new user
        authy.register_user(self.email, self.phone, self.countryCode,
            function(err, response) {
            if(err){
                if(response && response.json) {
                    response.json(err);
                } else {
                    console.error(err);
                }
                return;
            }
            self.authyId = response.user.id;
            self.save(function(err, doc) {
                if (err || !doc) return next(err);
                self = doc;
            });
        });
    };
});

// Test candidate password
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    var self = this;
    bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

// Send a OneTouch request to this user
UserSchema.methods.sendOneTouch = function(cb) {
    var self = this;
    self.authyStatus = 'unverified';
    self.save();

    onetouch.send_approval_request(self.authyId, {
        message: 'Request to Login to Twilio demo app',
        email: self.email
    }, function(err, authyres){
        if (err && err.success != undefined) {
            authyres = err;
            err = null;
        }
        cb.call(self, err, authyres);
    });
};

// Send a 2FA token to this user
UserSchema.methods.sendAuthyToken = function(cb) {
    var self = this;

    authy.request_sms(self.authyId, function(err, response) {
        cb.call(self, err);
    });
};

// Test a 2FA token
UserSchema.methods.verifyAuthyToken = function(otp, cb) {
    var self = this;
    authy.verify(self.authyId, otp, function(err, response) {
        cb.call(self, err, response);
    });
};

// Export user model
module.exports = mongoose.model('User', UserSchema);

```

## Log in with Authy OneTouch

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:

* We attempt to send a User a *[OneTouch Approval Request](/docs/authy/api)*
* 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

```js title="Log in with Authy OneTouch" description="api/sessions.js"
// !mark(10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,7,8,9)
var Session = require('../models/Session');
var User = require('../models/User');
var error = require('./response_utils').error;
var ok = require('./response_utils').ok;

// Create a new session, first testing username/password combo
exports.create = function(request, response) {
    var email = request.body.email;
    var candidatePassword = request.body.password;

    // Look for a user by the given username
    User.findOne({
        email: email
    }, function(err, user) {
        if (err || !user) return invalid();

        // We have a user for that username, test password
        user.comparePassword(candidatePassword, function(err, match) {
            if (err || !match) return invalid();
            return valid(user);
        });
    });

    // respond with a 403 for a login error
    function invalid() {
        error(response, 403, 'Invalid username/password combination.');
    }

    // respond with a new session for a valid password, and send a 2FA token
    function valid(user) {
        Session.createSessionForUser(user, false, function(err, sess, authyResponse) {
            if (err || !sess) {
                error(response, 500,
                    'Error creating session - please log in again.');
            } else {
                // Send the unique token for this session and the onetouch response
                response.send({
                    token: sess.token,
                    authyResponse: authyResponse
                });
            }
        });
    }
};

// Destroy the given session (log out)
exports.destroy = function(request, response) {
    request.session && request.session.remove(function(err, doc) {
        if (err) {
            error(response, 500, 'There was a problem logging you out - please retry.');
        } else {
            ok(response);
        }
    });
};

// Public webhook for Authy to POST to
exports.authyCallback = function(request, response) {
    var authyId = request.body.authy_id;

    // Respond with a 404 for a no user found error
    function invalid() {
        error(response,
            404,
            'No user found.'
        );
    }

    // Look for a user with the authy_id supplies
    User.findOne({
        authyId: authyId
    }, function(err, user) {
        if (err || !user) return invalid();
        user.authyStatus = request.body.status;
        user.save();
    });
    response.end();
};

// Internal endpoint for checking the status of OneTouch
exports.authyStatus = function(request, response) {
    var status = (request.user) ? request.user.authyStatus : 'unverified';
    if (status == 'approved') {
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');
        });
    }
    if (!request.session) {
        return error(response, 404, 'No valid session found for this user.');
    } else {
        response.send({ status: status });
    }
};

// Validate a 2FA token
exports.verify = function(request, response) {
    var oneTimeCode = request.body.code;

    if (!request.session || !request.user) {
        return error(response, 404, 'No valid session found for this token.');
    }

    // verify entered authy code
    request.user.verifyAuthyToken(oneTimeCode, function(err) {
        if (err) return error(response, 401, 'Invalid confirmation code.');

        // otherwise we're good! Validate the session
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');

            response.send({
                token: request.session.token
            });
        });
    });
};

// Resend validation code
exports.resend = function(request, response) {
    if (!request.user) return error(response, 404,
        'No user found for this session, please log in again.');

    // Otherwise resend the code
    request.user.sendAuthyToken(function(err) {
        if (!request.user) return error(response, 500,
            'No user found for this session, please log in again.');

        ok(response);
    });
};
```

## Send the OneTouch Request

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:

```bash
details = {
  message: "Request to send money to Jarod's vault",
  from: "Jarod",
  amount: "1,000,000",
  currency: "Galleons"
}

```

```js title="Send the OneTouch request" description="models/User.js"
// !mark(100,101,102,103,104,105,106,107,108,109,93,94,95,96,97,98,99)
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var config = require('../config');
var onetouch = require('../api/onetouch');

// Create authenticated Authy API client
var authy = require('authy')(config.authyApiKey);

// Used to generate password hash
var SALT_WORK_FACTOR = 10;

// Define user model schema
var UserSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required: true
    },
    countryCode: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    authyId: String,
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    authyStatus: {
        type: String,
        default: 'unverified'
    }
});

// Middleware executed before save - hash the user's password
UserSchema.pre('save', function(next) {
    var self = this;

    // only hash the password if it has been modified (or is new)
    if (!self.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(self.password, salt, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            self.password = hash;
            next();
        });
    });

    if (!self.authyId) {
        // Register this user if it's a new user
        authy.register_user(self.email, self.phone, self.countryCode,
            function(err, response) {
            if(err){
                if(response && response.json) {
                    response.json(err);
                } else {
                    console.error(err);
                }
                return;
            }
            self.authyId = response.user.id;
            self.save(function(err, doc) {
                if (err || !doc) return next(err);
                self = doc;
            });
        });
    };
});

// Test candidate password
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    var self = this;
    bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

// Send a OneTouch request to this user
UserSchema.methods.sendOneTouch = function(cb) {
    var self = this;
    self.authyStatus = 'unverified';
    self.save();

    onetouch.send_approval_request(self.authyId, {
        message: 'Request to Login to Twilio demo app',
        email: self.email
    }, function(err, authyres){
        if (err && err.success != undefined) {
            authyres = err;
            err = null;
        }
        cb.call(self, err, authyres);
    });
};

// Send a 2FA token to this user
UserSchema.methods.sendAuthyToken = function(cb) {
    var self = this;

    authy.request_sms(self.authyId, function(err, response) {
        cb.call(self, err);
    });
};

// Test a 2FA token
UserSchema.methods.verifyAuthyToken = function(otp, cb) {
    var self = this;
    authy.verify(self.authyId, otp, function(err, response) {
        cb.call(self, err, response);
    });
};

// Export user model
module.exports = mongoose.model('User', UserSchema);

```

***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.*

## 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.

```js title="Update user status using Authy Callback" description="api/sessions.js"
// !mark(57,58,59,60,61,62,63,64,65,66,67,68,69,70)
var Session = require('../models/Session');
var User = require('../models/User');
var error = require('./response_utils').error;
var ok = require('./response_utils').ok;

// Create a new session, first testing username/password combo
exports.create = function(request, response) {
    var email = request.body.email;
    var candidatePassword = request.body.password;

    // Look for a user by the given username
    User.findOne({
        email: email
    }, function(err, user) {
        if (err || !user) return invalid();

        // We have a user for that username, test password
        user.comparePassword(candidatePassword, function(err, match) {
            if (err || !match) return invalid();
            return valid(user);
        });
    });

    // respond with a 403 for a login error
    function invalid() {
        error(response, 403, 'Invalid username/password combination.');
    }

    // respond with a new session for a valid password, and send a 2FA token
    function valid(user) {
        Session.createSessionForUser(user, false, function(err, sess, authyResponse) {
            if (err || !sess) {
                error(response, 500,
                    'Error creating session - please log in again.');
            } else {
                // Send the unique token for this session and the onetouch response
                response.send({
                    token: sess.token,
                    authyResponse: authyResponse
                });
            }
        });
    }
};

// Destroy the given session (log out)
exports.destroy = function(request, response) {
    request.session && request.session.remove(function(err, doc) {
        if (err) {
            error(response, 500, 'There was a problem logging you out - please retry.');
        } else {
            ok(response);
        }
    });
};

// Public webhook for Authy to POST to
exports.authyCallback = function(request, response) {
    var authyId = request.body.authy_id;

    // Respond with a 404 for a no user found error
    function invalid() {
        error(response,
            404,
            'No user found.'
        );
    }

    // Look for a user with the authy_id supplies
    User.findOne({
        authyId: authyId
    }, function(err, user) {
        if (err || !user) return invalid();
        user.authyStatus = request.body.status;
        user.save();
    });
    response.end();
};

// Internal endpoint for checking the status of OneTouch
exports.authyStatus = function(request, response) {
    var status = (request.user) ? request.user.authyStatus : 'unverified';
    if (status == 'approved') {
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');
        });
    }
    if (!request.session) {
        return error(response, 404, 'No valid session found for this user.');
    } else {
        response.send({ status: status });
    }
};

// Validate a 2FA token
exports.verify = function(request, response) {
    var oneTimeCode = request.body.code;

    if (!request.session || !request.user) {
        return error(response, 404, 'No valid session found for this token.');
    }

    // verify entered authy code
    request.user.verifyAuthyToken(oneTimeCode, function(err) {
        if (err) return error(response, 401, 'Invalid confirmation code.');

        // otherwise we're good! Validate the session
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');

            response.send({
                token: request.session.token
            });
        });
    });
};

// Resend validation code
exports.resend = function(request, response) {
    if (!request.user) return error(response, 404,
        'No user found for this session, please log in again.');

    // Otherwise resend the code
    request.user.sendAuthyToken(function(err) {
        if (!request.user) return error(response, 500,
            'No user found for this session, please log in again.');

        ok(response);
    });
};
```

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.

## Disabling Unsuccessful Callbacks

**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

*Our user interface for this example is a [single page application](https://en.wikipedia.org/wiki/Single-page_application) written using [Backbone](https://backbonejs.org/) and [jQuery](https://jquery.com/).*

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.

```js title="Handle Two-Factor in the browser" description="public/app/views/Login.js"
(function() {
    app.views.LoginView = app.views.BaseView.extend({
        // name of the template file to load from the server
        templateName: 'login',

        // UI events
        events: {
            'submit #loginForm': 'login'
        },

        initialize: function() {
            var self = this;
            // default behavior, render page into #page section
            app.router.on('route:login', function() {
                self.render();
            });
        },

        // Hit login service
        login: function(e) {
            var self = this;

            e.preventDefault();
            app.set('message', null);
            $.ajax('/session', {
                method: 'POST',
                data: {
                    email: self.$('#email').val(),
                    password: self.$('#password').val()
                }
            }).done(function(data) {
                // If session returns oneTouch status.success wait for oneStatus approval
                app.set('token', data.token);
                if (data.authyResponse.success) {
                    app.set('onetouch', true);
                    app.set('message', {
                        error: false,
                        message: 'Awaiting One Touch approval.'
                    });
                    self.checkOneTouchStatus();
                } else {
                    app.router.navigate('verify', {
                        trigger: true
                    });
                }
            }).fail(function(err) {
                app.set('message', {
                    error: true,
                    message: err.responseJSON.message ||
                        'Sorry, an error occurred, please log in again.'
                });
            });
        },

        checkOneTouchStatus: function() {
            var self = this;
            $.ajax('/authy/status', {
                method: 'GET',
                headers: {
                    'X-API-TOKEN': app.get('token')
                }
            }).done(function(data) {
                if (data.status == 'approved') {
                    app.router.navigate('user', {
                        trigger: true
                    });
                } else if (data.status == 'denied') {
                    app.router.navigate('verify', {
                        trigger: true
                    });
                    app.set('message', {
                        error: true,
                        message: 'OneTouch Login request denied.'
                    });
                } else {
                    setTimeout(self.checkOneTouchStatus(), 3000);
                }
            });
        }
    });
})();
```

## Fall back to Authy Token

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.

```js title="Check login status and redirect if needed" description="api/sessions.js"
// !mark(72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87)
var Session = require('../models/Session');
var User = require('../models/User');
var error = require('./response_utils').error;
var ok = require('./response_utils').ok;

// Create a new session, first testing username/password combo
exports.create = function(request, response) {
    var email = request.body.email;
    var candidatePassword = request.body.password;

    // Look for a user by the given username
    User.findOne({
        email: email
    }, function(err, user) {
        if (err || !user) return invalid();

        // We have a user for that username, test password
        user.comparePassword(candidatePassword, function(err, match) {
            if (err || !match) return invalid();
            return valid(user);
        });
    });

    // respond with a 403 for a login error
    function invalid() {
        error(response, 403, 'Invalid username/password combination.');
    }

    // respond with a new session for a valid password, and send a 2FA token
    function valid(user) {
        Session.createSessionForUser(user, false, function(err, sess, authyResponse) {
            if (err || !sess) {
                error(response, 500,
                    'Error creating session - please log in again.');
            } else {
                // Send the unique token for this session and the onetouch response
                response.send({
                    token: sess.token,
                    authyResponse: authyResponse
                });
            }
        });
    }
};

// Destroy the given session (log out)
exports.destroy = function(request, response) {
    request.session && request.session.remove(function(err, doc) {
        if (err) {
            error(response, 500, 'There was a problem logging you out - please retry.');
        } else {
            ok(response);
        }
    });
};

// Public webhook for Authy to POST to
exports.authyCallback = function(request, response) {
    var authyId = request.body.authy_id;

    // Respond with a 404 for a no user found error
    function invalid() {
        error(response,
            404,
            'No user found.'
        );
    }

    // Look for a user with the authy_id supplies
    User.findOne({
        authyId: authyId
    }, function(err, user) {
        if (err || !user) return invalid();
        user.authyStatus = request.body.status;
        user.save();
    });
    response.end();
};

// Internal endpoint for checking the status of OneTouch
exports.authyStatus = function(request, response) {
    var status = (request.user) ? request.user.authyStatus : 'unverified';
    if (status == 'approved') {
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');
        });
    }
    if (!request.session) {
        return error(response, 404, 'No valid session found for this user.');
    } else {
        response.send({ status: status });
    }
};

// Validate a 2FA token
exports.verify = function(request, response) {
    var oneTimeCode = request.body.code;

    if (!request.session || !request.user) {
        return error(response, 404, 'No valid session found for this token.');
    }

    // verify entered authy code
    request.user.verifyAuthyToken(oneTimeCode, function(err) {
        if (err) return error(response, 401, 'Invalid confirmation code.');

        // otherwise we're good! Validate the session
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');

            response.send({
                token: request.session.token
            });
        });
    });
};

// Resend validation code
exports.resend = function(request, response) {
    if (!request.user) return error(response, 404,
        'No user found for this session, please log in again.');

    // Otherwise resend the code
    request.user.sendAuthyToken(function(err) {
        if (!request.user) return error(response, 500,
            'No user found for this session, please log in again.');

        ok(response);
    });
};
```

Now let's take a look at how we handle two-factor with tokens.

## Sending a 2FA Token

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.

```js title="Send and validate the authentication Token" description="models/User.js"
// !mark(111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126)
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var config = require('../config');
var onetouch = require('../api/onetouch');

// Create authenticated Authy API client
var authy = require('authy')(config.authyApiKey);

// Used to generate password hash
var SALT_WORK_FACTOR = 10;

// Define user model schema
var UserSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required: true
    },
    countryCode: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    authyId: String,
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    authyStatus: {
        type: String,
        default: 'unverified'
    }
});

// Middleware executed before save - hash the user's password
UserSchema.pre('save', function(next) {
    var self = this;

    // only hash the password if it has been modified (or is new)
    if (!self.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(self.password, salt, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            self.password = hash;
            next();
        });
    });

    if (!self.authyId) {
        // Register this user if it's a new user
        authy.register_user(self.email, self.phone, self.countryCode,
            function(err, response) {
            if(err){
                if(response && response.json) {
                    response.json(err);
                } else {
                    console.error(err);
                }
                return;
            }
            self.authyId = response.user.id;
            self.save(function(err, doc) {
                if (err || !doc) return next(err);
                self = doc;
            });
        });
    };
});

// Test candidate password
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    var self = this;
    bcrypt.compare(candidatePassword, self.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

// Send a OneTouch request to this user
UserSchema.methods.sendOneTouch = function(cb) {
    var self = this;
    self.authyStatus = 'unverified';
    self.save();

    onetouch.send_approval_request(self.authyId, {
        message: 'Request to Login to Twilio demo app',
        email: self.email
    }, function(err, authyres){
        if (err && err.success != undefined) {
            authyres = err;
            err = null;
        }
        cb.call(self, err, authyres);
    });
};

// Send a 2FA token to this user
UserSchema.methods.sendAuthyToken = function(cb) {
    var self = this;

    authy.request_sms(self.authyId, function(err, response) {
        cb.call(self, err);
    });
};

// Test a 2FA token
UserSchema.methods.verifyAuthyToken = function(otp, cb) {
    var self = this;
    authy.verify(self.authyId, otp, function(err, response) {
        cb.call(self, err, response);
    });
};

// Export user model
module.exports = mongoose.model('User', UserSchema);

```

## Validate the Code

Our Express route handler will grab the code submitted on the form in order to validate it. The [connect middleware](https://stephensugden.com/middleware_guide/) 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.

```js title="Validate the authentication token" description="api/sessions.js"
// !mark(100,101,102,103,104,105,106,107,108,109,110,111,112,89,90,91,92,93,94,95,96,97,98,99)
var Session = require('../models/Session');
var User = require('../models/User');
var error = require('./response_utils').error;
var ok = require('./response_utils').ok;

// Create a new session, first testing username/password combo
exports.create = function(request, response) {
    var email = request.body.email;
    var candidatePassword = request.body.password;

    // Look for a user by the given username
    User.findOne({
        email: email
    }, function(err, user) {
        if (err || !user) return invalid();

        // We have a user for that username, test password
        user.comparePassword(candidatePassword, function(err, match) {
            if (err || !match) return invalid();
            return valid(user);
        });
    });

    // respond with a 403 for a login error
    function invalid() {
        error(response, 403, 'Invalid username/password combination.');
    }

    // respond with a new session for a valid password, and send a 2FA token
    function valid(user) {
        Session.createSessionForUser(user, false, function(err, sess, authyResponse) {
            if (err || !sess) {
                error(response, 500,
                    'Error creating session - please log in again.');
            } else {
                // Send the unique token for this session and the onetouch response
                response.send({
                    token: sess.token,
                    authyResponse: authyResponse
                });
            }
        });
    }
};

// Destroy the given session (log out)
exports.destroy = function(request, response) {
    request.session && request.session.remove(function(err, doc) {
        if (err) {
            error(response, 500, 'There was a problem logging you out - please retry.');
        } else {
            ok(response);
        }
    });
};

// Public webhook for Authy to POST to
exports.authyCallback = function(request, response) {
    var authyId = request.body.authy_id;

    // Respond with a 404 for a no user found error
    function invalid() {
        error(response,
            404,
            'No user found.'
        );
    }

    // Look for a user with the authy_id supplies
    User.findOne({
        authyId: authyId
    }, function(err, user) {
        if (err || !user) return invalid();
        user.authyStatus = request.body.status;
        user.save();
    });
    response.end();
};

// Internal endpoint for checking the status of OneTouch
exports.authyStatus = function(request, response) {
    var status = (request.user) ? request.user.authyStatus : 'unverified';
    if (status == 'approved') {
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');
        });
    }
    if (!request.session) {
        return error(response, 404, 'No valid session found for this user.');
    } else {
        response.send({ status: status });
    }
};

// Validate a 2FA token
exports.verify = function(request, response) {
    var oneTimeCode = request.body.code;

    if (!request.session || !request.user) {
        return error(response, 404, 'No valid session found for this token.');
    }

    // verify entered authy code
    request.user.verifyAuthyToken(oneTimeCode, function(err) {
        if (err) return error(response, 401, 'Invalid confirmation code.');

        // otherwise we're good! Validate the session
        request.session.confirmed = true;
        request.session.save(function(err) {
            if (err) return error(response, 500,
                'There was an error validating your session.');

            response.send({
                token: request.session.token
            });
        });
    });
};

// Resend validation code
exports.resend = function(request, response) {
    if (!request.user) return error(response, 404,
        'No user found for this session, please log in again.');

    // Otherwise resend the code
    request.user.sendAuthyToken(function(err) {
        if (!request.user) return error(response, 500,
            'No user found for this session, please log in again.');

        ok(response);
    });
};
```

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

## Where to next?

If you're a Node.js developer working with Twilio, you might want to check out these other tutorials.

**[Account Verification](/docs/authy/tutorials/account-verification-node-express)**

Increase the security of your login system by verifying a user's mobile phone.

**[Server Notifications via SMS](/blog/server-notifications-node-express)**

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.
