Enable Two Factor Auth

Two factor authentication (2FA) is a way to add an extra layer of security to your user's accounts. It requires them to enter a code from another device (usually their phone) in addition to their username and password. The device is the second "factor" (in addition to the password) that is used to verify the user's identity.
With this, even if an attacker were able to determine a user's password, they wouldn't be able to log in without also having access to the user's phone. This makes it much harder for an attacker to gain access to a user's account.
This requires a bit of work to set up, but it's worth it for the extra security and it's become a standard feature in many apps.
Because we've already implemented verifications for our signup, forgot password, and change email flow, much of the work is already done. 2FA is just another type of verification. The biggest differences from what we've done already are:
  • This verification won't have an expiration
  • The period will be much shorter (30 seconds)
  • The code will be generated by the user's 2FA app instead of being sent to them via email
We're breaking up the whole 2FA flow in multiple exercises. For this first part of the exercise, we'll just allow the user to enable 2FA on their account. Let's take a look at the steps for what you'll be implementing:
A diagram showing actions taken by a user, server, 2fa app, and a verification in the database
Here are the steps:
  • The user enables 2FA in their account settings
  • The server creates a "verify verification" meaning a verification that will be used to verify the user can generate 2FA codes.
  • The server provides the user with an Auth URI (and a QR code to make it easy to add to their verification app).
  • The user scans the QR code to add it to their 2FA app (like 1Password).
  • The 2FA app generates a 6 digit code that is valid for 30 seconds.
  • The user submits that code
  • The server verifies the code
  • The server upgrades the verification from a "verify" type of verification to a "2FA" verification.
And that's as far as we're going to take it in this exercise. Let's go!