In this episode, we dive into the trickiest part of our two-factor authentication (2FA) flow: building the modal that lets users enable 2FA, shows them a QR code, and gives them a place to enter their authentication code.
First up, we refactor our existing code and extract the 2FA logic into its own dedicated form component, just like we did with our change password form. We add a button for enabling 2FA, but only show it if 2FA isn't already enabled for the user.
Behind the scenes, we wire up the user model with the necessary trait so it can handle 2FA, and expose whether or not 2FA is enabled directly on the user resource. This lets us control when the enable/disable buttons are visible in the UI.
Next, when the enable button gets clicked, we send a POST request to Fortify to actually enable 2FA for the user. This sets up all the required data (like the secret and recovery codes) in the database. But at this point, the process isn’t complete—we still need the user to scan their QR code and confirm their setup.
That’s where the modal comes in! We set up routes, controllers, and a simple modal component to handle showing the QR code and form for entering the 2FA code. We also make sure our modal pops up right after enabling 2FA, creating a seamless flow.
By the end of this episode, our enablement flow is mostly in place. The user can click to enable 2FA and instantly see a modal, set up with everything they'll need to complete the process. In the next episode, we'll finish up the flow by actually showing the QR code, letting users scan it with their authentication app, and verifying their code.