Invisible Captcha : how to avoid spam in Rails
If you got a public website and you got a form that can be edited from users (like a contact form for example), you will get spammed every day. How to deal with it ?
Spambots become stronger day after day. When we dev a new form we have to deal with security to avoir injections, but sometimes we have to avoid with spam. Imagine you got a website with a contact form, how will you do to stop spambots ?
There are man ways to do it, you can try to :
- Ask a question to the user (example : Give me result for 4+4)
- Use a captcha (like google captcha)
- Disallow links in content form
- Use a blacklist of words or adresses extension
But all of these are not really good because of user experience (you stop the user in his way to complete the form asking a question or filling a captcha), or just because it’s hard to deal with a blacklist.
Honeypot to the rescue !
Another approach is to use the honeypot principle : add in your form an input that won’t be visible by the user, will have to stay empty, but bots will complete it. This is the simple first way, but it’s not suffisant.
Bots test your website and to check if they complete your form, they are waiting for the response. So you have to catch them before submit (to block usual action), and give them a “200 response OK”.
Invisible-captcha’s gem
In a Rails project, there is a gem to do it : invisible-captcha :
#Gemfile
gem 'invisible_captcha'
#app/controller/contact_controller.rb
class ContactController < ApplicationController
invisible_captcha only: [:create]
def create
# check params
Notification.my_contact_form(params).deliver
end
end
#app/views/contact/index.html.erb
<%= form_tag(envoyer_message_contact_index_path) do %>
<%= invisible_captcha %>
<%= text_field_tag "name", nil, placeholder: "Name", required: true %>
<%= text_field_tag "email", nil, placeholder: "Email", required: true %>
#(...)
<% end %>
You can choose to params this honeypot’s gem with many options, like custom the name of the field, choose what do to with callback etc.
Github invisible-captcha