Skip to content

How To: Use Recaptcha with Devise

avioing edited this page Mar 21, 2011 · 63 revisions

WARNING: The first draft of this page was done by a total n00b. There wasn't any help here for Recaptcha before, so he hopes this does help some people, but other more experienced should clean this up at a later date.

  1. Get your keys from Google/Recaptcha
  2. Install the Recaptcha gem found here (note: for Rails 3 do gem 'recaptcha', :require => 'recaptcha/rails')
  3. Add <%= recaptcha_tags %> on your New Registration view (you must have generated Devise views) the line before your submit button.
  4. Create/Update your RegistrationsController - see the "controllers" section in the README to understand how to set up your own devise controllers, and don't forget to update the routes once you do. Remember that "devise" expects you to use flash[:notice] and flash[:alert] and not flash[:error]. Include the following (the first is for a clean Devise install, and the second is for if you use OmniAuth like me): Clean:
  class RegistrationsController < Devise::RegistrationsController
  
    def create
      if verify_recaptcha
        super
      else
        build_resource
        clean_up_passwords(resource)
        flash[:alert] = "There was an error with the recaptcha code below. Please re-enter the code and click submit."
        render_with_scope :new
      end
    end
    .
    .
    .
    .
  end

With OmniAuth:

  class RegistrationsController < Devise::RegistrationsController
  
    def create
      if session[:omniauth] == nil #OmniAuth
        if verify_recaptcha
          super
          session[:omniauth] = nil unless @user.new_record? #OmniAuth
        else
          build_resource
          clean_up_passwords(resource)
          flash[:alert] = "There was an error with the recaptcha code below. Please re-enter the code and click submit."
          render_with_scope :new
        end
      else
        super
        session[:omniauth] = nil unless @user.new_record? #OmniAuth
      end
    end

Clone this wiki locally