1
3

More than 1 year has passed since last update.

Rails Recaptcha v3を導入する

Posted at

Ruby on Railsでinvisible reCAPTCHAを導入しました。

参考リンク
https://developers.google.com/recaptcha/docs/v3

最初はRecaptchaのSiteKeyとSecret Keyを作成する
https://www.google.com/recaptcha/admin/create

Front側:

<% provide(:title, "Log in") %>
<script src="https://www.google.com/recaptcha/api.js?render=<%= @recaptcha_sitekey %>"> </script>
<script type="text/javascript">
  function onClick(e) {
    grecaptcha.ready(function() {
      grecaptcha.execute(document.getElementById('sitekey').value, {action: 'submit'}).then(function(token) {
          document.getElementById("recaptcha_response").value = token
          document.getElementById("demo-form").submit();
      });
    });
  }
</script>
<section class="h-100 gradient-form" style="background-color: #eee; width: 900px;">
  <div class="container py-5 h-100">
    <div class="row d-flex justify-content-center align-items-center h-100">
    <%= form_for(:login, url: logins_create_path, id: "demo-form") do |f| %>
      <div class="col-xl-10" style="display: flex; flex-direction: column;">
        <div class="card rounded-3 text-black">
          <div class="row g-0">
            <div class="col-lg-6">
              <div class="card-body p-md-5 mx-md-4">

                <div class="text-center">
                  <img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-login-form/lotus.webp"
                    style="width: 185px;" alt="logo">
                </div>
                  <p>Please login to your account</p>

                  <div class="form-outline mb-4">
                    <input type="email" id="form2Example11" class="form-control"
                      placeholder="Phone number or email address" />
                       <%= f.label :email %>
                  </div>

                  <div class="form-outline mb-4">
                    <input type="password" id="form2Example22" class="form-control" />
                     <%= f.label :password %>
                  </div>
                  <div class="text-center pt-1 mb-5 pb-1">
                    <input type="hidden" name="recaptcha_response" id="recaptcha_response">
                   <input type="hidden" name="sitekey" id="sitekey" value=<%= @recaptcha_sitekey %> >
                    <button class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="button" onclick="onClick(this)">Log in</button>
                    <br><a class="text-muted" href="#!">Forgot password?</a>
                  </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    <% end %>
    </div>
  </div>
</section>
<style type="text/css">
.btn {
  margin-top: 30px;
  
  width: 300px;
  height: 50px;
  border: 1px solid green;
  background: lightblue;   
}
.row {
    width: 80%;
    margin: auto;
}
.gradient-custom-2 {
/* fallback for old browsers */
background: #fccb90;

/* Chrome 10-25, Safari 5.1-6 */
background: -webkit-linear-gradient(to right, #ee7724, #d8363a, #dd3675, #b44593);

/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
background: linear-gradient(to right, #ee7724, #d8363a, #dd3675, #b44593);
}

@media (min-width: 768px) {
.gradient-form {
height: 100vh !important;
}
}
@media (min-width: 769px) {
.gradient-custom-2 {
border-top-right-radius: .3rem;
border-bottom-right-radius: .3rem;
}
}
</style>

Backend側:

require 'uri'
require 'net/http'
class LoginsController < ApplicationController
  
  # 上で作成したSecretKeyを設定
  RECAPTCHA_SECRET_KEY = '6LcpSyElAAAAAGOo1JB9t7W4njhefrtgh-fgf'
  RECAPTCHA_SITEVERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'

  # ログインページ初期化
  def new
    @data = User.new
    @recaptcha_sitekey = '6LcpSyElAAAAAGOo1JB9t7W4njhefrtgh'
  end
  
  # ログイン処理
  def create
    siteverify_uri = URI.parse("#{RECAPTCHA_SITEVERIFY_URL}?response=#{params[:recaptcha_response]}&secret=#{RECAPTCHA_SECRET_KEY}")
    response = Net::HTTP.get_response(siteverify_uri)
    json_response = JSON.parse(response.body)
    puts "score =========== #{json_response['score']} "

    # Recaptchaが成功の場合
    if json_response['success'] && json_response['score'] > 0.5
      # ログイン情報チェック
      user = User.new
      data = user.find_by_login_id(login_parameter)
      # Login情報が一致しない場合、ログインページへ移動
      if data.nil?
        render action: "new"
      else
        # Topページへ移動
        redirect_to controller: :things, action: :index
      end
    else
      # Recaptcha失敗の場合、ログインページへ移動
      render :new
    end
  end
  
  private
  def login_parameter
    params.require(:login).permit(
      :email,
      :password
    )
  end
end


RecaptchaV3導入出来ました。
p1.png

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3