Skip to contentSkip to navigationSkip to topbar
On this page

Account Verification with Authy, Ruby and Rails


(warning)

Warning

As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.

For new development, we encourage you to use the Verify v2 API.

Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see Migrating from Authy to Verify for SMS(link takes you to an external page).

Ready to implement user account verification in your application? Here's how it works at a high level:

  1. The user begins the registration process by entering their data, including a phone number, into a signup form.
  2. The authentication system sends a one-time password to the user's mobile phone to verify their possession of that phone number.
  3. The user enters the one-time password into a form before completing registration.
  4. The user sees a success page and receives an SMS indicating that their account has been created.

Building Blocks

building-blocks page anchor

To get this done, you'll be working with the following Twilio-powered APIs:

Authy REST API

Twilio REST API

  • Messages Resource: We will use Twilio directly to send our user a confirmation message after they create an account.

Let's get started!


In this tutorial, we will be working through a series of user stories(link takes you to an external page) that describe how to fully implement account verification in a web application. Our team implemented this example application in about 12 story points (roughly equivalent to 12 working hours).

Let's get started with our first user story around creating a new user account.


As a user, I want to register for a new user account with my email, full name, mobile phone number, and a password.

To do account verification, you need to start with an account. This requires that we create a bit of UI and a model object to create and save a new User in our system. At a high level, here's what we will need to add:

  • A form to enter details about the new user
  • A route and controller function on the server to render the form
  • A route and controller function on the server to handle the form POST request
  • A persistent User model object to store information about the user

Let's start by looking at the model, where we decide what information we want to store about our user.


Let's start by defining our model and validating it.

First we need to create the ActiveRecord object, which creates the model in the related Postgres table and tells our app how to validate the model's data.

Data Validation

data-validation page anchor

Validations are important since we want to make sure only accurate data is being saved into our database. In this case we only want to validate that all of our required fields are present. We can do this by creating a validates statement with presence: true.

Calling has_secure_password in Rails creates a hash that protects our user's passwords in the database.

One note: in order to run this demo you would need to run rake db:migrate which would run the migrations in our db/migrate folder. For this tutorial we're going to focus on the verification steps, but if you want to learn more about migrations you can read the Rails guide(link takes you to an external page) on the subject.

Create a user model and its associated properties

create-a-user-model-and-its-associated-properties page anchor

app/models/user.rb

1
class User < ActiveRecord::Base
2
has_secure_password
3
4
validates :email, presence: true, format: { with: /\A.+@.+$\Z/ }, uniqueness: true
5
validates :name, presence: true
6
validates :country_code, presence: true
7
validates :phone_number, presence: true
8
end
9

Now we're ready to move up to the controller level of the application, starting with the HTTP request routes we'll need.


In a Rails(link takes you to an external page) application, there is something called Resource Routing(link takes you to an external page) which automatically maps a resource's CRUD capabilities to its controller. Since our User is an ActiveRecord resource, we can tell Rails that we want to use some of these routes, which will save us some lines of code.

This means that in this one line of code we automatically have a 'user/new' route which will render our 'user/new.html.erb' file.

Create application routes

create-application-routes page anchor

config/routes.rb

1
Rails.application.routes.draw do
2
3
get "users/verify", to: 'users#show_verify', as: 'verify'
4
post "users/verify"
5
post "users/resend"
6
7
# Create users
8
resources :users, only: [:new, :create, :show]
9
10
# Home page
11
root 'main#index'
12
13
end

Let's take a look at the new user form up close.


When we create a new user, we ask for a name, email address, and a password. In order to validate their account with Authy, we also ask them for a mobile number with a country code, which we can use to send them one-time passwords via SMS.

By using the rails form_for tag we can bind the form to the model object. This will generate the necessary html markup that will create a new User on submit.

app/views/users/new.html.erb

1
<h1>We're going to be *BEST* friends</h1>
2
<p> Thanks for your interest in signing up! Can you tell us a bit about yourself?</p>
3
4
<% if @user.errors.any? %>
5
<h2>Oops, something went wrong!</h2>
6
7
<ul>
8
<% @user.errors.full_messages.each do |error| %>
9
<li><%= error %></li>
10
<% end -%>
11
</ul>
12
<% end -%>
13
14
<%= form_for @user do |f| %>
15
<div class="form-group">
16
<%= f.label :name, "Tell us your name:" %>
17
<%= f.text_field :name, class: "form-control", placeholder: "Zingelbert Bembledack" %>
18
</div>
19
<div class="form-group">
20
<%= f.label :email, "Enter Your email Address:" %>
21
<%= f.email_field :email, class: "form-control", placeholder: "me@mydomain.com" %>
22
</div>
23
<div class="form-group">
24
<%= f.label :password, "Enter a password:" %>
25
<%= f.password_field :password, class: "form-control" %>
26
</div>
27
<div class="form-group">
28
<%= f.label :country_code %>
29
<%= f.text_field :country_code, class: "form-control", id: "authy-countries" %>
30
</div>
31
<div class="form-group">
32
<%= f.label :phone_number %>
33
<%= f.text_field :phone_number, class: "form-control", id: "authy-cellphone" %>
34
</div>
35
<button class="btn btn-primary">Sign up</button>
36
<% end -%>
37

Let's jump back over to the controller to see what happens when we create a user.


One of the other handy controllers created by our User resource route is 'user/create' which handles the POST from our form.

In our controller we take the input from our form and create a new User model. If the user is saved to the database successfully, we use the Authy gem to create a corresponding Authy User and save the ID for that user in our database.

Create a new user and register user with Authy

create-a-new-user-and-register-user-with-authy page anchor

app/controllers/users_controller.rb

1
class UsersController < ApplicationController
2
def new
3
@user = User.new
4
end
5
6
def show
7
@user = current_user
8
end
9
10
def create
11
@user = User.new(user_params)
12
if @user.save
13
# Save the user_id to the session object
14
session[:user_id] = @user.id
15
16
# Create user on Authy, will return an id on the object
17
authy = Authy::API.register_user(
18
email: @user.email,
19
cellphone: @user.phone_number,
20
country_code: @user.country_code
21
)
22
@user.update(authy_id: authy.id)
23
24
# Send an SMS to your user
25
Authy::API.request_sms(id: @user.authy_id)
26
27
redirect_to verify_path
28
else
29
render :new
30
end
31
end
32
33
def show_verify
34
return redirect_to new_user_path unless session[:user_id]
35
end
36
37
def verify
38
@user = current_user
39
40
# Use Authy to send the verification token
41
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
42
43
if token.ok?
44
# Mark the user as verified for get /user/:id
45
@user.update(verified: true)
46
47
# Send an SMS to the user 'success'
48
send_message("You did it! Signup complete :)")
49
50
# Show the user profile
51
redirect_to user_path(@user.id)
52
else
53
flash.now[:danger] = "Incorrect code, please try again"
54
render :show_verify
55
end
56
end
57
58
def resend
59
@user = current_user
60
Authy::API.request_sms(id: @user.authy_id)
61
flash[:notice] = 'Verification code re-sent'
62
redirect_to verify_path
63
end
64
65
private
66
67
def send_message(message)
68
@user = current_user
69
twilio_number = ENV['TWILIO_NUMBER']
70
account_sid = ENV['TWILIO_ACCOUNT_SID']
71
@client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']
72
message = @client.api.accounts(account_sid).messages.create(
73
:from => twilio_number,
74
:to => @user.country_code+@user.phone_number,
75
:body => message
76
)
77
end
78
79
def user_params
80
params.require(:user).permit(
81
:email, :password, :name, :country_code, :phone_number
82
)
83
end
84
end
85

Now we have a user that has registered, but is not yet verified. In order to view anything else on the site they need to verify that they own the phone number they submitted by entering a token we send to that phone. Time to take a look at how we would send this token.


User Story: Sending a One-Time Password

user-story-sending-a-one-time-password page anchor

As an authentication system, I want to send a one-time password to a user's mobile phone to verify their possession of that phone number.

This story covers a process that is invisible to the end user but necessary to power our account verification functionality. After a new user is created, the application needs to send a one-time password to that user's phone to validate the number (and the account). Here's what needs to get done:

  • Create and configure an Authy API client.
  • Modify the controller to send a one-time password after the user is created.

Let's begin by modifying the app's configuration to contain our Authy API key.


In secrets.yml, we list configuration parameters for the application. Most are pulled in from system environment variables, which is a helpful way to access sensitive values (like API keys). This prevents us from accidentally checking them in to source control.

Now, we need our Authy production key (sign up for Authy here(link takes you to an external page)). When you create an Authy application, the production key is found on the dashboard:

Authy dashboard.

Define configuration parameters used in the application

define-configuration-parameters-used-in-the-application page anchor

config/secrets.yml

1
# Be sure to restart your server when you modify this file.
2
3
# Your secret key is used for verifying the integrity of signed cookies.
4
# If you change this key, all old signed cookies will become invalid!
5
6
# Make sure the secret is at least 30 characters and all random,
7
# no regular words or you'll be exposed to dictionary attacks.
8
# You can use `rake secret` to generate a secure secret key.
9
10
# Make sure the secrets in this file are kept private
11
# if you're sharing your code publicly.
12
13
development:
14
secret_key_base: 2995cd200a475082070d5ad7b11c69407a6219b0b9bf1f747f62234709506c097da19f731ecf125a3fb53694ee103798d6962c199603b92be8f08b00bf6dbb18
15
authy_key: <%= ENV["AUTHY_API_KEY"] %>
16
17
test:
18
secret_key_base: deff24bab059bbcceeee98afac8df04814c44dd87d30841f8db532a815b64387d69cfd3d09a78417869c4846f133ba7978068882ca0a96626136ebd084b70732
19
authy_key: <%= ENV["AUTHY_API_KEY"] %>
20
21
# Do not keep production secrets in the repository,
22
# instead read values from the environment.
23
production:
24
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
25
authy_key: <%= ENV["AUTHY_API_KEY"] %>
26

Next, we need to jump over to the UserController to configure the Authy client and create an instance method to send a one-time password.


Sending a Token on Account Creation

sending-a-token-on-account-creation page anchor

Once the user has an authyId, we can actually send a verification code to that user's mobile phone.

When our user is created successfully via the form we implemented for the last story, we send a token to the user's mobile phone to verify their account in our controller.

Send an SMS to your user and re-direct to the user's verification page

send-an-sms-to-your-user-and-re-direct-to-the-users-verification-page page anchor

app/controllers/users_controller.rb

1
class UsersController < ApplicationController
2
def new
3
@user = User.new
4
end
5
6
def show
7
@user = current_user
8
end
9
10
def create
11
@user = User.new(user_params)
12
if @user.save
13
# Save the user_id to the session object
14
session[:user_id] = @user.id
15
16
# Create user on Authy, will return an id on the object
17
authy = Authy::API.register_user(
18
email: @user.email,
19
cellphone: @user.phone_number,
20
country_code: @user.country_code
21
)
22
@user.update(authy_id: authy.id)
23
24
# Send an SMS to your user
25
Authy::API.request_sms(id: @user.authy_id)
26
27
redirect_to verify_path
28
else
29
render :new
30
end
31
end
32
33
def show_verify
34
return redirect_to new_user_path unless session[:user_id]
35
end
36
37
def verify
38
@user = current_user
39
40
# Use Authy to send the verification token
41
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
42
43
if token.ok?
44
# Mark the user as verified for get /user/:id
45
@user.update(verified: true)
46
47
# Send an SMS to the user 'success'
48
send_message("You did it! Signup complete :)")
49
50
# Show the user profile
51
redirect_to user_path(@user.id)
52
else
53
flash.now[:danger] = "Incorrect code, please try again"
54
render :show_verify
55
end
56
end
57
58
def resend
59
@user = current_user
60
Authy::API.request_sms(id: @user.authy_id)
61
flash[:notice] = 'Verification code re-sent'
62
redirect_to verify_path
63
end
64
65
private
66
67
def send_message(message)
68
@user = current_user
69
twilio_number = ENV['TWILIO_NUMBER']
70
account_sid = ENV['TWILIO_ACCOUNT_SID']
71
@client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']
72
message = @client.api.accounts(account_sid).messages.create(
73
:from => twilio_number,
74
:to => @user.country_code+@user.phone_number,
75
:body => message
76
)
77
end
78
79
def user_params
80
params.require(:user).permit(
81
:email, :password, :name, :country_code, :phone_number
82
)
83
end
84
end
85

When the code is sent, we redirect to another page where the user can enter the token they were sent, completing the verification process.


User Story: Verify the One-Time Password

user-story-verify-the-one-time-password page anchor

As a user, I want to enter the one-time password sent to my mobile phone from the authentication system before I complete the signup process.

This story covers the next user-facing step of the verification process, where they enter the code we sent them to verify their possession of the phone number they gave us. Here's what needs to get done to complete this story:

  • Create a form to allow the user to enter the one-time password they were sent.
  • Create routes and controllers to both display the form and handle the submission of the one-time password.

Form to verify a one-time password

form-to-verify-a-one-time-password page anchor

app/views/users/show_verify.html.erb

1
<h1>Just To Be Safe...</h1>
2
<p>
3
Your account has been created, but we need to make sure you're a human
4
in control of the phone number you gave us. Can you please enter the
5
verification code we just sent to your phone?
6
</p>
7
<%= form_tag users_verify_path do %>
8
<div class="form-group">
9
<%= label_tag :code, "Verification Code:" %>
10
<%= text_field_tag :token, '', class: "form-control" %>
11
</div>
12
<button type="submit" class="btn btn-primary">Verify Token</button>
13
<% end -%>
14
15
<hr>
16
<%= form_tag users_resend_path do %>
17
<button type="submit" class="btn">Resend code</button>
18
<% end -%>
19

The route definition in config/routes.rb is pretty straight-forward, so we'll skip that bit here. Let's begin instead with the verification form, which is created with the Embedded Ruby Template code you see here.


This page actually has two forms, but we'll focus on the form for verifying a user's code first. It has only a single field for the verification code, which we'll submit to the server for validation.

Form to verify a one-time password

form-to-verify-a-one-time-password-1 page anchor

app/views/users/show_verify.html.erb

1
<h1>Just To Be Safe...</h1>
2
<p>
3
Your account has been created, but we need to make sure you're a human
4
in control of the phone number you gave us. Can you please enter the
5
verification code we just sent to your phone?
6
</p>
7
<%= form_tag users_verify_path do %>
8
<div class="form-group">
9
<%= label_tag :code, "Verification Code:" %>
10
<%= text_field_tag :token, '', class: "form-control" %>
11
</div>
12
<button type="submit" class="btn btn-primary">Verify Token</button>
13
<% end -%>
14
15
<hr>
16
<%= form_tag users_resend_path do %>
17
<button type="submit" class="btn">Resend code</button>
18
<% end -%>
19

Now let's take a look at the controller code handling this form.


Verifying the Code: Controller

verifying-the-code-controller page anchor

This controller function handles the form submission. It needs to:

  • Get the current user.
  • Verify the code that was entered by the user.
  • If the code entered was valid, flip a Boolean flag on the user model to indicate the account was verified.

Authy provides us with a verify method that allows us to pass a user id, a token and a callback function if we'd like. In this case we just need to check that the API request was successful and, if so, set user.verified to true.

Handle Authy verification and confirmation

handle-authy-verification-and-confirmation page anchor

app/controllers/users_controller.rb

1
class UsersController < ApplicationController
2
def new
3
@user = User.new
4
end
5
6
def show
7
@user = current_user
8
end
9
10
def create
11
@user = User.new(user_params)
12
if @user.save
13
# Save the user_id to the session object
14
session[:user_id] = @user.id
15
16
# Create user on Authy, will return an id on the object
17
authy = Authy::API.register_user(
18
email: @user.email,
19
cellphone: @user.phone_number,
20
country_code: @user.country_code
21
)
22
@user.update(authy_id: authy.id)
23
24
# Send an SMS to your user
25
Authy::API.request_sms(id: @user.authy_id)
26
27
redirect_to verify_path
28
else
29
render :new
30
end
31
end
32
33
def show_verify
34
return redirect_to new_user_path unless session[:user_id]
35
end
36
37
def verify
38
@user = current_user
39
40
# Use Authy to send the verification token
41
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
42
43
if token.ok?
44
# Mark the user as verified for get /user/:id
45
@user.update(verified: true)
46
47
# Send an SMS to the user 'success'
48
send_message("You did it! Signup complete :)")
49
50
# Show the user profile
51
redirect_to user_path(@user.id)
52
else
53
flash.now[:danger] = "Incorrect code, please try again"
54
render :show_verify
55
end
56
end
57
58
def resend
59
@user = current_user
60
Authy::API.request_sms(id: @user.authy_id)
61
flash[:notice] = 'Verification code re-sent'
62
redirect_to verify_path
63
end
64
65
private
66
67
def send_message(message)
68
@user = current_user
69
twilio_number = ENV['TWILIO_NUMBER']
70
account_sid = ENV['TWILIO_ACCOUNT_SID']
71
@client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']
72
message = @client.api.accounts(account_sid).messages.create(
73
:from => twilio_number,
74
:to => @user.country_code+@user.phone_number,
75
:body => message
76
)
77
end
78
79
def user_params
80
params.require(:user).permit(
81
:email, :password, :name, :country_code, :phone_number
82
)
83
end
84
end
85

That's all for this story! However, our verification form wouldn't be very usable if there wasn't a way to resend a verification code if the message didn't arrive at the end user's handset for whatever reason. Let's look at that next.


Since the form for re-sending the code is one line (see show_verify.html.erb) we're going to skip that for this tutorial. Let's just look at the controller function.

This controller loads the User model associated with the request and then uses the same Authy API method we used earlier to resend the code. Pretty straightforward!

Re-send Authy code to current user

re-send-authy-code-to-current-user page anchor

app/controllers/users_controller.rb

1
class UsersController < ApplicationController
2
def new
3
@user = User.new
4
end
5
6
def show
7
@user = current_user
8
end
9
10
def create
11
@user = User.new(user_params)
12
if @user.save
13
# Save the user_id to the session object
14
session[:user_id] = @user.id
15
16
# Create user on Authy, will return an id on the object
17
authy = Authy::API.register_user(
18
email: @user.email,
19
cellphone: @user.phone_number,
20
country_code: @user.country_code
21
)
22
@user.update(authy_id: authy.id)
23
24
# Send an SMS to your user
25
Authy::API.request_sms(id: @user.authy_id)
26
27
redirect_to verify_path
28
else
29
render :new
30
end
31
end
32
33
def show_verify
34
return redirect_to new_user_path unless session[:user_id]
35
end
36
37
def verify
38
@user = current_user
39
40
# Use Authy to send the verification token
41
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
42
43
if token.ok?
44
# Mark the user as verified for get /user/:id
45
@user.update(verified: true)
46
47
# Send an SMS to the user 'success'
48
send_message("You did it! Signup complete :)")
49
50
# Show the user profile
51
redirect_to user_path(@user.id)
52
else
53
flash.now[:danger] = "Incorrect code, please try again"
54
render :show_verify
55
end
56
end
57
58
def resend
59
@user = current_user
60
Authy::API.request_sms(id: @user.authy_id)
61
flash[:notice] = 'Verification code re-sent'
62
redirect_to verify_path
63
end
64
65
private
66
67
def send_message(message)
68
@user = current_user
69
twilio_number = ENV['TWILIO_NUMBER']
70
account_sid = ENV['TWILIO_ACCOUNT_SID']
71
@client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']
72
message = @client.api.accounts(account_sid).messages.create(
73
:from => twilio_number,
74
:to => @user.country_code+@user.phone_number,
75
:body => message
76
)
77
end
78
79
def user_params
80
params.require(:user).permit(
81
:email, :password, :name, :country_code, :phone_number
82
)
83
end
84
end
85

To wrap things up, let's implement our last user story where we confirm the user's account creation and verification.


User Story: Confirm Account Creation

user-story-confirm-account-creation page anchor

As a user, I want to view a success page and receive a text message indicating that my account has been created successfully.

This story completes the account verification use case by indicating to the user that their account has been created and verified successfully. To implement this story, we need to:

  • Display a page that indicates that the user account has been created and verified successfully.
  • Send a text message to the user's phone indicating their account has been verified.

Account creation & verification confirmation page

account-creation--verification-confirmation-page page anchor

app/views/users/show.html.erb

1
<h1><%= @user.name %></h1>
2
<p>Account Status: <% if @user.verified? %>Verified<% else -%>Not Verified<% end -%>
3
<% if !@user.verified? %>
4
<p>
5
<%= link_to "Verify your account now.", verify_path %>
6
</p>
7
<% end -%>

This .erb template displays a user name and let's them know they've been verified.

Just a reminder that our router is automatically looking for a 'show.html.erb' template to render since we told it to use Resource Routing which automatically creates a users/show/:id route.

Account creation & verification confirmation page

account-creation--verification-confirmation-page-1 page anchor

app/views/users/show.html.erb

1
<h1><%= @user.name %></h1>
2
<p>Account Status: <% if @user.verified? %>Verified<% else -%>Not Verified<% end -%>
3
<% if !@user.verified? %>
4
<p>
5
<%= link_to "Verify your account now.", verify_path %>
6
</p>
7
<% end -%>

This should suffice for in-browser confirmation that the user has been verified. Let's see how we might send that text message next.


Authy is awesome for abstracting SMS and handling 2FA and account verification, but we can't use it to send arbitrary text messages. Let's use the Twilio API directly to do that!

In order to use the 'twilio-ruby' helper library(link takes you to an external page) we just need to include it in our Gemfile.

But first, we need to configure our Twilio account. We'll need three things, all of which can be found or set up through the Twilio console(link takes you to an external page):

  • Our Twilio account SID
  • Our Twilio auth token
  • A Twilio number in our account that can send text messages

Configure Twilio and Authy in your application

configure-twilio-and-authy-in-your-application page anchor
1
source 'https://rubygems.org'
2
3
4
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
5
gem 'rails', '4.2.3'
6
# Use postgresql as the database for Active Record
7
gem 'pg'
8
# Use SCSS for stylesheets
9
gem 'sass-rails', '~> 5.0'
10
# Use Uglifier as compressor for JavaScript assets
11
gem 'uglifier', '>= 1.3.0'
12
# Use CoffeeScript for .coffee assets and views
13
gem 'coffee-rails', '~> 4.1.0'
14
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
15
# gem 'therubyracer', platforms: :ruby
16
17
# Use jquery as the JavaScript library
18
gem 'jquery-rails'
19
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
20
gem 'turbolinks'
21
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
22
gem 'jbuilder', '~> 2.0'
23
# bundle exec rake doc:rails generates the API under doc/api.
24
gem 'sdoc', '~> 0.4.0', group: :doc
25
26
# Use ActiveModel has_secure_password
27
gem 'bcrypt', '~> 3.1.7'
28
29
# Use Authy for sending token
30
gem 'authy'
31
32
# Use Twilio to send confirmation message
33
gem 'twilio-ruby', '~>5.0.0'
34
35
# Use Unicorn as the app server
36
gem 'unicorn'
37
38
group :production do
39
gem 'rails_12factor'
40
end
41
42
group :development do
43
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
44
gem 'byebug'
45
46
# Access an IRB console on exception pages or by using <%= console %> in views
47
gem 'web-console', '~> 2.0'
48
49
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
50
gem 'spring'
51
52
# Mocha for mocking
53
gem 'mocha'
54
end

Sending a Message: Using the Twilio client

sending-a-message-using-the-twilio-client page anchor

Much as we did for our Authy client, we create a single instance of the Twilio REST API helper, called @client in this example.

Then all we need to do to send an sms is use the built in messages.create() to send an SMS to the user's phone. Notice we are combing country_code and phone_number to make sure we support international numbers.

Send message to user with Twilio

send-message-to-user-with-twilio page anchor

app/controllers/users_controller.rb

1
class UsersController < ApplicationController
2
def new
3
@user = User.new
4
end
5
6
def show
7
@user = current_user
8
end
9
10
def create
11
@user = User.new(user_params)
12
if @user.save
13
# Save the user_id to the session object
14
session[:user_id] = @user.id
15
16
# Create user on Authy, will return an id on the object
17
authy = Authy::API.register_user(
18
email: @user.email,
19
cellphone: @user.phone_number,
20
country_code: @user.country_code
21
)
22
@user.update(authy_id: authy.id)
23
24
# Send an SMS to your user
25
Authy::API.request_sms(id: @user.authy_id)
26
27
redirect_to verify_path
28
else
29
render :new
30
end
31
end
32
33
def show_verify
34
return redirect_to new_user_path unless session[:user_id]
35
end
36
37
def verify
38
@user = current_user
39
40
# Use Authy to send the verification token
41
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
42
43
if token.ok?
44
# Mark the user as verified for get /user/:id
45
@user.update(verified: true)
46
47
# Send an SMS to the user 'success'
48
send_message("You did it! Signup complete :)")
49
50
# Show the user profile
51
redirect_to user_path(@user.id)
52
else
53
flash.now[:danger] = "Incorrect code, please try again"
54
render :show_verify
55
end
56
end
57
58
def resend
59
@user = current_user
60
Authy::API.request_sms(id: @user.authy_id)
61
flash[:notice] = 'Verification code re-sent'
62
redirect_to verify_path
63
end
64
65
private
66
67
def send_message(message)
68
@user = current_user
69
twilio_number = ENV['TWILIO_NUMBER']
70
account_sid = ENV['TWILIO_ACCOUNT_SID']
71
@client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']
72
message = @client.api.accounts(account_sid).messages.create(
73
:from => twilio_number,
74
:to => @user.country_code+@user.phone_number,
75
:body => message
76
)
77
end
78
79
def user_params
80
params.require(:user).permit(
81
:email, :password, :name, :country_code, :phone_number
82
)
83
end
84
end
85

Sending a Message: Updating the Controller

sending-a-message-updating-the-controller page anchor

In the controller, after a new user has been successfully verified, we use send_message to deliver them the happy news!

app/controllers/users_controller.rb

1
class UsersController < ApplicationController
2
def new
3
@user = User.new
4
end
5
6
def show
7
@user = current_user
8
end
9
10
def create
11
@user = User.new(user_params)
12
if @user.save
13
# Save the user_id to the session object
14
session[:user_id] = @user.id
15
16
# Create user on Authy, will return an id on the object
17
authy = Authy::API.register_user(
18
email: @user.email,
19
cellphone: @user.phone_number,
20
country_code: @user.country_code
21
)
22
@user.update(authy_id: authy.id)
23
24
# Send an SMS to your user
25
Authy::API.request_sms(id: @user.authy_id)
26
27
redirect_to verify_path
28
else
29
render :new
30
end
31
end
32
33
def show_verify
34
return redirect_to new_user_path unless session[:user_id]
35
end
36
37
def verify
38
@user = current_user
39
40
# Use Authy to send the verification token
41
token = Authy::API.verify(id: @user.authy_id, token: params[:token])
42
43
if token.ok?
44
# Mark the user as verified for get /user/:id
45
@user.update(verified: true)
46
47
# Send an SMS to the user 'success'
48
send_message("You did it! Signup complete :)")
49
50
# Show the user profile
51
redirect_to user_path(@user.id)
52
else
53
flash.now[:danger] = "Incorrect code, please try again"
54
render :show_verify
55
end
56
end
57
58
def resend
59
@user = current_user
60
Authy::API.request_sms(id: @user.authy_id)
61
flash[:notice] = 'Verification code re-sent'
62
redirect_to verify_path
63
end
64
65
private
66
67
def send_message(message)
68
@user = current_user
69
twilio_number = ENV['TWILIO_NUMBER']
70
account_sid = ENV['TWILIO_ACCOUNT_SID']
71
@client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']
72
message = @client.api.accounts(account_sid).messages.create(
73
:from => twilio_number,
74
:to => @user.country_code+@user.phone_number,
75
:body => message
76
)
77
end
78
79
def user_params
80
params.require(:user).permit(
81
:email, :password, :name, :country_code, :phone_number
82
)
83
end
84
end
85

Congratulations! You now have the power to register and verify users with Authy and Twilio SMS.

If you're a Ruby developer working with Twilio, you might want to check out these other tutorials:

Click To Call

Put a button on your web page that connects visitors to live support or sales people via telephone.

Automated Survey(link takes you to an external page)

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.