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:

class AddPhoneNumberToUsers < ActiveRecord::Migration
  def change
    add_column :users, :phone_number, :string

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"  %>

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


class ApplicationController < ActionController::Base
  before_action :authenticate_user!

  protect_from_forgery with: :exception

  before_filter :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:account_update, keys: [:phone_number])

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