Dylan Steck Dylan Steck - 5 months ago 7
Ruby Question

Using Nexmo Verify to Login to a Ruby Sinatra App

I have found a ruby on rails 2fa nexmo verify tutorial but some of it doesn't work on Sinatra because the frameworks have some differences and it doesn't fit what I'm making. Can anyone help me out or lead me in the path of using Nexmo Verify in my Sinatra app?

post "/" do
client = Nexmo::Client.new(key: 'mykey', secret: 'mysecret')
response = client.send_verification_request(number params[:phonenumber], brand: 'OpenINC')
if response['status'] == '0'
erb :code
else
erb :error
end
end

get'/code' do
erb :code
end

post '/code' do
client = Nexmo::Client.new(key: 'mykey', secret: 'mysecret')
response = client.check_verification_request(code: '1234', request_id: '00e6c3377e5348cdaf567e1417c707a5')

if response['status'] == '0'
erb :start
else
erb :error
end
end


Where it says mykey and mysecret I put my key and secret but just didn't want to put my actual key and secret on Stack OverFlow

Answer

Based on the code above, and that in the repo, the problem is simply that the request_id and code values are hard-coded.

If you:

  1. Store the request_id from the response to the response = client.send_verification_request(number: params[:phonenumber], brand: 'OpenINC') call e.g. session[:request_id] = response['request_id']
  2. Get the code that the user submits in the post /code route e.g. code = params[:code]
  3. Retrieve the request_id from the session in the post /code route e.g. request_id = session[:request_id]
  4. Use the code and request_id when checking the verification request e.g. `check_verification_request(code: code, request_id: request_id)

Then the code will work.

Full basic example:

post "/" do
  client = Nexmo::Client.new(key: 'mykey', secret: 'mysecret')
  response = client.send_verification_request(number: params[:phonenumber], brand: 'OpenINC')

  # 1. Store request_id
  session[:request_id] = response['request_id']

  if response['status'] == '0'
    erb :code
  else
    erb :error
  end
end

get'/code' do
  erb :code
end

post '/code' do
  # 2. Get the user verification code
  code = params[:code]

  # 3. Retrieve the request_id
  request_id = session[:request_id]

  client = Nexmo::Client.new(key: 'mykey', secret: 'mysecret')

  # 4. Use the code and request_id
  response = client.check_verification_request(code: code, request_id: request_id)

  if response['status'] == '0'
    erb :start
  else
    erb :error
   end
end

I've also submitted a PR against your repo here with this commit containing the main details.