Search code examples
ruby-on-railsrubyrecaptchaspam-prevention

reading parameters from create method


I have a ruby on rails project that is using the devise gem for authentication. I'm trying to use a captcha form in the sign up page to prevent bots from creating thousands of dummy logins

I'm not interested in using the recaptcha gem that works with devise as I haven't had any luck setting it up correctly.

I trying to set it up using this as a reference https://recaptchainrubyonrails.blogspot.com/

Here's my sign up page

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: 
registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>

<div class="field">
  <%= f.label :email %><br />
  <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>

<div class="field">
  <%= f.label :password %>
  <% if @minimum_password_length %>
  <em>(<%= @minimum_password_length %> characters minimum)</em>
  <% end %><br />
  <%= f.password_field :password, autocomplete: "off" %>
</div>

<div class="field">
  <%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>

<div class="g-recaptcha" data 
sitekey="6LeeL5gUAAAAADbq0vt4d9biAs8oegkPx9ttUkKb"></div>

<div class="actions">
  <%= f.submit "Sign up" %>
</div>
<% end %>
<br>

I do have my routes file point to a separate registrations controller instead of the one created within the devise registrations

devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout' }, :controllers => {:registrations => "registrations"}

I can create a user regardless if I click on the captcha form. When I do click on it I get the parameter, g-recaptcha-response, in the create method that has a long text string such as

"g-recaptcha-response"=>"1234567890abcdefghi..."

I tried a create method that would look at that parameter and see if it is not nil. When it is nil I would like to back one page to the sign up page.

class RegistrationsController < Devise::RegistrationsController

  def create
      if not params[:g-recaptcha-response].present?
        redirect_to :back
      end
  end
end 

I can't even get to the parameter as it errors out saying

undefined local variable or method `recaptcha' for #<RegistrationsController:0x7219e5a0> Did you mean? catch"

I'm trying to capture this parameter, look at the value of g-recaptcha-response and somehow cancel the creation of a user if the response was nil or empty string


Solution

  • Use 'g-recaptcha-response' instead of :g-recaptcha-response. You need to use string syntax because you cannot use - in symbol naming