Authentication with Mobile Numbers in Rails using Devise

Many applications use mobile number authentication instead of email-based authentication. This article will discuss the technique to override default authentication behavior. Here are the steps to authenticate using a mobile number:

1
rails new phone_authenticate

Add devise in your Gemfile.

1
gem 'devise'

Run bundle install. Then, in your terminal:

1
2
rails generate devise:install
rails generate devise User

Remove the following line, generated by devise, from the migration, then run rails db:migrate:

1
add_index :users, :email,                unique: true

Now make a controller and its view.

1
rails generate controller home index

In app/controllers/home_controller.rb put the following line:

1
before_action :authenticate_user!

In config/routes.rb, put this line:

1
root to: 'home#index'

In your app/views/layouts/application.html.erb, put the following lines:

1
2
3
<%= link_to "Logout", destroy_user_session_path, method: 'delete' %>
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

The basic setup is done now. Moving onto the main topic - in your config/initializers/devise.rb, put the following line:

1
config.authentication_keys = [:phone]

Put the following code in app/models/user.rb:

1
2
3
4
5
6
7
8
9
validates :phone, uniqueness: true

def email_required?
 false
end

def email_changed?
 false
end

Time to add the phone field in the users table. Go ahead and create a migration.

1
2
rails g migration add_phone_to_users
rails db:migrate

Put the following code in the migration file:

1
2
3
4
5
class AddPhoneToUsers < ActiveRecord::Migration[6.0]
 def change
   add_column :users, :phone, :string
 end
end

Run rails db:migrate.

Edit your views and put your new field in the form.

1
rails generate devise:views -v registrations sessions

In your app/views/devise/registrations/new.html.erb, delete the field related to email and add the following lines:

1
2
3
4
<div class="field">
 <%= f.label :phone %><br />
 <%= f.text_field :phone, autofocus: true %>
</div>

In your app/views/devise/sessions/new.html.erb, delete the field related to email and add the following lines:

1
2
3
4
<div class="field">
 <%= f.label :phone %><br />
 <%= f.text_field :phone, autofocus: true %>
</div>

That’s it - happy authenticating!