認証コードを確認する

プロセスの最後の部分は、ユーザーに受信したコードを入力させ、Verify APIから送信されたコードと一致することを確認することである。

まず、新しいルートを追加する:

config/routes.rb

Rails.application.routes.draw do
  devise_for :users
  resources :verifications, only: [:edit, :update]

  root to: 'kittens#index'
end

次に、基本的なコントローラを作成する:

app/controllers/verifications_controller.rb

class VerificationsController < ApplicationController
  skip_before_action :verify_user!
 
  def edit
  end
 
  def update
  end
end

をスキップすることが重要である。 before_action に追加した。 ApplicationController ブラウザがリダイレクトの無限ループに陥らないようにするためだ。

ユーザーが認証コードを入力できるようにするビューを作成します:

app/views/verifications/edit.html.erb

<div class="panel panel-default devise-bs">
  <div class="panel-heading">
    <h4>Verify code</h4>
  </div>
  <div class="panel-body">
    <%= form_tag verification_path(id: params[:id]), method: :put do %>
      <div class="form-group">
        <%= label_tag :code %><br />
        <%= number_field_tag :code, class: "form-control"  %>
      </div>
      <%= submit_tag 'Verify', class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

<%= link_to 'Send me a new code', :root %>

その後、ユーザーはコードを新しい update アクションを実行します。このアクションの中で request_id そして code に渡す。 check_verification_request メソッドを使用する:

app/controllers/verifications_controller.rb

def update
  confirmation = Vonage::Client.new.verify.check(
    request_id: params[:id],
    code: params[:code]
  )
 
  if confirmation['status'] == '0'
    session[:verified] = true
    redirect_to :root, flash: { success: 'Welcome back.' }
  else
    redirect_to edit_verification_path(id: params[:id]), flash[:error] = confirmation['error_text'] 
  end
end

検証チェックが成功すると、ユーザーのステータスはVerifyに設定され、メインページにリダイレクトされます。チェックに失敗した場合は、何が問題であったかを説明するメッセージが表示されます。

セキュリティとスパム防止のための二要素認証

Rubyアプリケーションに2faを実装する方法を学ぶ

手順
1
はじめに
2
基本アプリケーションの作成
3
電話番号必須
4
検証リクエストの送信
5
認証コードを確認する
6
お試しあれ!