DEV Community

Code Salley
Code Salley

Posted on

Rails Dummy OTP verification with Nexmo API / Twilio

I recently stumbled on a web app based on helping people who need donations during this pandemic, but one thing I couldn't get right was sending OTP for phone number verifications since email was optional.
I decided to come up with a dummy idea!

Create a user table with a column for saving a temporary generated OTP code, and a column to set account state.

  create_table "users", force: :cascade do |t|
    t.string "email"
    t.string "phone_number"
    t.boolean "verified", default: false
    t.string "tmp_code"
   end
Enter fullscreen mode Exit fullscreen mode

Implement a method to generate a number from 1012 to 9292, in this case, I will always have numbers of length 4

class User < ApplicationRecord
  after_create :set_sms_code

  private
  def set_sms_code
    code = Random.rand(1012..9292)
    self.tmp_code = code
  end
end
Enter fullscreen mode Exit fullscreen mode

In my controller, when a user enters a verification code. I catch it from the params and check it against the one I had saved in the database.

  def verify_code
    if current_user.tmp_code === params[:confirmation_code]
      current_user.update(activated: true)
      redirect_to root_path, notice: "account activated"
    else
      flash[:alert] = "invalid code"
      render :welcome
    end
  end
Enter fullscreen mode Exit fullscreen mode

I know this was a dummy and probably unhealthy, I, later on, had a background job to set it to a different number every 30 minutes and resend it to the user.

Next: Part ||

Top comments (0)