I am using the reCAPTCHA gem (https://github.com/ambethia/recaptcha) on my form in Ruby on Rails. I am encountering a problem when the user submits a form that has an error (like they forget a field). When the form is rendered again with the errors, it seems like no matter what, the recaptcha always submits false, even though it shows a checkmark. If I reload the page, then it works fine. Is there a way to fix this problem?
Update: I am using the recaptcha on a user signup page, and have essentially followed the code from the gem github page.
Form View:
<%= form_with(model: @user) do |f| %>
<%= render :partial => 'shared/error_messages', :locals => { :object => @user} %>
<%= f.label :firstname, "First Name" %>
<%= f.text_field :firstname, class: 'form-control' %>
<%= f.label :lastname, "Last Name" %>
<%= f.text_field :lastname, class: 'form-control' %>
<%= f.label :email, "E-mail Address" %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.label :password, "Password" %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<center><%= recaptcha_tags %></center>
<br>
<%= f.submit "Create New User", class: "btn btn-primary" %>
<% end %>
And in the controller:
def create
@user = User.new(user_params)
if verify_recaptcha(model: @user) && @user.save
@user.send_activation_email
flash[:info] = "Please check your email to activate your account"
redirect_to root_url
else
render 'new', status: :unprocessable_entity
end
end
I can see in the parameters when the form is submitted the first time that the g-recaptcha-response exists. But each subsequent time after a form validation error occurs, the g-recaptcha-response is empty and I get the "reCAPTCHA verification failed, please try again". This also ignores other form validation errors and only displays the recaptcha error if I submit the form again with form errors.
I have tried using both the enterprise version and the classic version, and have ensured that the keys are correct. I am using the V2 version that requires a checkmark for "i'm not a robot"
This issue might be related to Turbo, which tries to replace a full page reload by just replacing several pieces of the web page. While this usually works fine, it obviously does not in this case.
I assume that the captcha-challenge is used twice so Google denies the captcha in the second (or third...) try.
Try to disable Turbo for your login form by replacing
<%= form_with(model: @user) do |f| %>
with
<%= form_with(model: @user, local: true, data: {turbo: "false"} ) do |f| %>
For a closer look at Turbo, visit this