Require a phone number

Start by requiring that users include a phone number when registering. Do this by generating a new database migration:

rails generate migration add_phone_number_to_users

Edit the db/migrate/..._add_phone_number_to_users.rb file to add a new column to the user model:

Apply the change by executing:

rake db:migrate

Devise provides a Rails generator for creating a copy of the templates you need to edit. You run the generator using the command rails generate:devise:views:templates.

However, because the sample application uses the devise-bootstrap-templates gem, you need to use a different version of the generator:

rails generate devise:views:bootstrap_templates

This copies multiple view templates into app/views/devise, but you are only interested in app/views/devise/registrations/edit.html.erb, so delete the rest.

Then, amend the edit template to add a field for the user to enter a phone number, directly after the email field:

<div class="form-group">
  <%= f.label :phone_number %> <i>(Leave blank to disable two factor authentication)</i><br />
  <%= f.number_field :phone_number, class: "form-control", placeholder: "e.g. 447555555555 or 1234234234234"  %>
</div>

Finally, you need to make Devise aware of this extra parameter:

app/controllers/application_controller.rb

To add a phone number to your account, run rails server, then navigate to http://localhost:3000/ and log in using the account details you registered with in the previous step.

Click your email address at the top right of the screen, enter your phone number and the password you used to register with and click Update. This will save your phone number to the database.

Two-factor authentication for security and spam prevention

Learn how to implement 2fa in your Ruby applications

Steps
1
Introduction
2
Create the basic application
3
Require a phone number
4
Send the verification request
5
Check the verification code
6
Try it out!