📜 ⬆️ ⬇️

Phone number verification using Ruby on rails and Twilio

Once I had the task to make a confirmation of the phone number. And, since I have absolutely no stars on the githab ( and invites on Habré ), it was decided to make a heme.

image

Twilio service was chosen as an SMS gateway, because it is convenient and inexpensive. Having spent on this thing a few hours, it turned out, as for me, a very convenient heme.

To install it, you need to add to the gemfile:
')
gem "twilio_phone_verification" 

Then execute the command:

 bundle install 

AND

 rails g twilio_phone_verification:install [USER_CLASS] 

USER_CLASS is the class for which you want to add a phone check. Note: it is necessary that this class has a name field so that it can send an SMS message “Hello, {{name}} ...” . This will create 2 files:

config / initializers / twilio_phone_verification.rb config file, where you must enter the keys and phone number from Twilio

 TwilioPhoneVerification.configure do |config| config.account_sid = ENV.fetch("TWILIO_ACCOUNT_SID") # Paste account id here config.auth_token = ENV.fetch("TWILIO_AUTH_TOKEN") # Paste your twilio auth token here config.from = ENV.fetch("TWILIO_NUMBER") # Paste your twilio number here end 

and db / migrate / 000000000000000_add_phone_to_users.rb migration, which will create the required fields:

 class AddPhoneToUsers < ActiveRecord::Migration[5.0] def self.up add_column :users, :phone, :string add_column :users, :phone_confirmation_token, :string add_column :users, :phone_confirmed_at, :datetime add_column :users, :phone_confirmation_sent_at, :datetime add_index :users, :phone, unique: true end def self.down remove_column :users, :phone remove_column :users, :phone_confirmation_token remove_column :users, :phone_confirmed_at remove_column :users, :phone_confirmation_sent_at end end 

Then execute the command:

 rails db:migrate # rails 5 rake db:migrate # rails < 5 

And add a conserv to the model so that the necessary methods are added:

 class User < ActiveRecord::Base include TwilioPhoneVerification::Phonable end 

This will add 4 basic methods: phone_confirmed? returns true or false , depending on whether the phone is confirmed.

send_phone_confirmation generates a code and sends a text message . Returns {success: true} if the SMS has been sent, or false if it has not. Every time a new sms is generated. And the code can only be sent once per minute.

confirm_phone_by_code (code) returns true and verifies the phone number if the code is correct, otherwise false .

confirm_phone verifies the phone number without checking the code.

If the method returns false , the error is added to .errors .

There are also 2 timestamps:

phone_confirmed_at when the phone was confirmed
phone_confirmation_sent_at when the last SMS was sent

» Github repo

That's all. Thanks for attention.

Source: https://habr.com/ru/post/314254/


All Articles