-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: Use Recaptcha with Devise
sourcecor edited this page Jul 6, 2016
·
63 revisions
To add Google's ReCaptcha to your site:
- Install the ReCaptcha gem
- Add
<%= recaptcha_tags %>
to your view. - Include a
prepend_before_action
for any action you want to secure:
class RegistrationsController < Devise::RegistrationsController
prepend_before_action :check_captcha, only: [:create] # Change this to be any actions you want to protect.
private
def check_captcha
unless verify_recaptcha
self.resource = resource_class.new sign_up_params
respond_with_navigational(resource) { render :new }
end
end
end
- If you are adding reCaptcha in registration page then add the below lines in config/routes.rb. The first one is configuration of devise generated controller (rails g devise:controller [scope]), but if you are using your own "registrations_controller.rb" then use it accordingly.
a) For Devise Generated Controller Route Settings (config/routes.rb):
devise_for :users, controllers: { ... , registrations: "user/registrations", ... }
b) For custom "registrations_controller.rb" in "app/controller" directory, use this Route Settings (config/routes.rb):
devise_for :users, controllers: { ... , registrations: "registrations", ... }
show recaptcha error, add below line, where you want show flash, ex. registrations\new.html.erb
<%= flash[:recaptcha_error] %> # <== add this one
<%= recaptcha_tags %>
Some of the available options for #verify_recaptcha
can be found here