Search code examples
ruby-on-railsdevisetwilioauthy

Adding Verification only to rails app with Authy, Twillio and Devise


Im building out a dispatch app with Rails 5, Ruby 2.4.0 and want to incorporate Twillio for SMS Authy (only for phone verification) and Devise for user authentication.

My question is following the Twillio tutorial Twillio Authy verification tutroial Do I want to create a custom devise registrations controller for this workflow or is it better to create a custom user controller to handle this?

As my app sits now an "owner" a class of User is created through a nested form on the account create action. Im just not sure that if I will hit the user controller on a create user through my account controller..?

This my be a garbage question, but im really lost here not sure how to proceed.


Solution

  • Baking the SMS verification into the standard Devise flow seems like an excellent idea instead of duplicating the functionality. Fortunately its pretty easy:

    class TwillioRegistrationsController < Devise::RegistrationsController
    
      def create
        super do |user|
          authy = Authy::API.register_user(
            email: user.email,
            cellphone: user.phone_number,
            country_code: user.country_code
          )
          user.update(authy_id: authy.id)
        end
      end
    
      protected
    
      def after_sign_up_path_for(resource)
        "users/verify"
      end
    end
    

    Devise lets you "tap" into the flow of almost all the controller methods by yielding. Devise::RegistrationsController#create yields the resource after it has been saved which is the perfect place to put the twillio logic.

    You then need to permit the additional parameters in devise and customize the form with additional fields.

    class ApplicationController < ActionController::Base
      def configure_permitted_parameters
         devise_parameter_sanitizer.permit(:sign_up, keys: [:phone_number, :country_code])
      end
    end
    

    Note that you still need to setup a controller to handle verifications, but you can do that by following the tutorial.