How to do Twilio Two Factor Authentication By Authy APP, SMS, And Phone Call Method By Using Authy-devise gem In Ruby On Rails

Ali Ahmad
2 min readJun 29, 2020

What is Twilio API?

Twilio is a platform which you can use to apply Two Factor verification for your App. it can send code on authy app, SMS or A phone call.

Things needed before starting

  1. Twilio account by visiting https://www.twilio.com/try-twilio
  2. Make a app on twilio, so you will get app key from there.
Save your API KEY

Install gems!

gem 'devise'
gem 'devise-authy'

Add Devise Authy to your App:

rails g devise_authy:install--haml: Generate the views in Haml
--sass: Generate the stylesheets in Sass

Configuring Models

You can add devise_authy to your user model in two ways.

go to App/config/initializers/authy.rb

require ‘authy’
Authy.api_key = ENV[‘AUTHY_API_KEY’] →your api key in ENV variable
Authy.api_uri = ‘https://api.authy.com/'

With the generator

This is the easiest way and is recommended. Run the following command:

rails g devise_authy [MODEL_NAME]

Manually

Add :authy_authenticatable to the devise options in your Devise user model:

devise :authy_authenticatable, :database_authenticatable

Add migration to your Devise model

class DeviseAuthyAddToUsers < ActiveRecord::Migration[6.0]
def self.up
change_table :users do |t|
t.string :authy_id
t.datetime :last_sign_in_with_authy
t.boolean :authy_enabled, :default => false
end

add_index :users, :authy_id
end

def self.down
change_table :users do |t|
t.remove :authy_id, :last_sign_in_with_authy, :authy_enabled
end
end
end

Final steps

For either method above, run the migrations:

rake db:migrate

[Optional] Update the default routes to point to something like:

devise_for :users, :path_names => {
:verify_authy => "/verify-token",
:enable_authy => "/enable-two-factor",
:verify_authy_installation => "/verify-installation",
:authy_onetouch_status => "/onetouch-status"
}

IF you want to override your controller than

# frozen_string_literal: truemodule Users
class DeviseAuthyController < Devise::DeviseAuthyController
.... your override methods
protecteddef after_authy_enabled_path_for(_resource)
root_path
end
def after_authy_verified_path_for(_resource)
root_path
end
def after_authy_disabled_path_for(_resource)
root_path
end
def invalid_resource_path
root_path
end
end

For Phone call use this method in views

<%= authy_request_phone_call_link %>

For SMS use this method in views

<%= authy_request_sms_link %>

You can edit your authy views in app/views/devise/devise_authy path.

--

--