reCAPTCHA v2

Episode #282 by David Kimura

Summary

Reduce the number of bots and spam your Ruby on Rails application gets with Google reCAPTCHA v2.
authentication rails security 11:10

Resources

Summary

# Terminal
bundle add recaptcha
rails credentials:edit --environment development
rails g devise:views

# config/credentials/development.yml.enc
recaptcha_site_key: YOUR_GOOGLE_SITE_KEY
recaptcha_secret_key: YOUR_GOOGLE_SECRET_KEY

# or use Environment variables RECAPTCHA_SITE_KEY and RECAPTCHA_SECRET_KEY

# config/initializers/recaptcha.rb
Recaptcha.configure do |config|
  config.site_key = Rails.application.credentials.recaptcha_site_key
  config.secret_key = Rails.application.credentials.recaptcha_secret_key
end

# views/devise/registrations/new.html.erb
  <div class="field">
    <%= flash[:recaptcha_error] %>
    <%= recaptcha_tags %>
  </div>

# config/routes.rb
devise_for :users, controllers: { registrations: "users/registrations" }

# controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
  prepend_before_action :check_captcha, only: :create

  private

  def check_captcha
    unless verify_recaptcha
      self.resource = resource_class.new sign_up_params
      resource.validate
      set_minimum_password_length
      respond_with_navigational(resource) { render :new }
    end
  end
end