- Setting up reCAPTCHA for Rails with the reCAPTCHA gem? It's easier than it sounds! Follow the instructions below with your own project or clone this one just to test it. Message Bill with any questions! Let's destroy the bots together!
- Request a free reCAPTCHA key from Google: https://www.google.com/recaptcha/admin
- Setup your reCAPTCHA key to work with localhost and any other domains you want:
- Drop this code into your rails app's Gemfile. Include the doteenv gem first, before the recaptcha gem is loaded. Alternatively, choose your own API key security solution.
gem 'dotenv-rails', :require => 'dotenv/rails-now'
gem "recaptcha", require: "recaptcha/rails"
- Run "bundle install" in your terminal to install both gems
-
Create a .env file in the root directory of your app.
-
In the .env file, include the following two lines:
export RECAPTCHA_PUBLIC_KEY = 'YOUR_PUBLIC_KEY'
export RECAPTCHA_PRIVATE_KEY = 'YOUR_PRIVATE_KEY'
- Include the .env file in your .gitignore, to be absolutely sure it's not being uploaded to github.
# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
# git config --global core.excludesfile '~/.gitignore_global'
# Ignore bundler config.
/.bundle
# Ignore all logfiles and tempfiles.
/log/*
!/log/.keep
/tmp
.env
- Setup is complete! Almost done! Now you just have to add one line (<%= recaptcha_tags %>) to the form you want to protect:
<%= form_for @foo do |f| %>
<%= f.text_field :sample_data %>
<%= recaptcha_tags %>
<% end %>
- Lastly just add a reCAPTCHA check to the controller that you want to protect (verify_recaptcha(model: @model)), then you're done!
@user = User.new(params[:user].permit(:name))
if verify_recaptcha(model: @user) && @user.save
redirect_to @user
else
render 'new'
end
- You did it! Bots can eat it. Ask Bill if you have any questions!
- [Bill Himmelsbach] (https://github.com/billhimmelsbach)