• Stars
    star
    82
  • Rank 382,721 (Top 8 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

reCAPTCHA v3 Ruby on Rails gem

Google Recaptcha v3 + Rails

Build Status RailsJazz https://www.patreon.com/igorkasyanchuk Listed on OpenSource-Heroes.com

Integrate Google Recaptcha v3 with Rails app.

Google Recaptcha console: https://www.google.com/recaptcha/admin#list

Recaptcha v3 documentation: https://developers.google.com/recaptcha/docs/v3

Usage

  • Open https://www.google.com/recaptcha/admin#list
  • register a new site
  • copy site_key and secret_key and put into config/initializers/new_google_recaptcha.rb
  • optionally, change the minimum_score in the initializer to a preferred float value (from 0.0 to 1.0)
  • in layout:
    <head>
      ...
      <%= yield :recaptcha_js %>
    </head>
  • in view where you for example you have a form:
    <%= content_for :recaptcha_js do %>
      <%= include_recaptcha_js %>
    <% end %>
    <form ...>
      <%#= 'checkout' is action name to be verified later %>
      <%= recaptcha_action('checkout') %>
    </form>
  • in controller:
    def create
      @post = Post.new(post_params)
      if NewGoogleRecaptcha.human?(
          params[:new_google_recaptcha_token],
          "checkout",
          NewGoogleRecaptcha.minimum_score,
          @post
        ) && @post.save
        redirect_to @post, notice: 'Post was successfully created.'
      else
        render :new
      end
    end
    
    
    # or
    # if you need to capture a humanity `score` from Google
    # before you need to add a column for example `humanity_score` (type: float) where this score will be saved.
    
    
    def create
      @post = Post.new(post_params)
      humanity_details =
        NewGoogleRecaptcha.get_humanity_detailed(
          params[:new_google_recaptcha_token],
          "checkout",
          NewGoogleRecaptcha.minimum_score,
          @post
        )
    
      @post.humanity_score = humanity_details[:score]
    
      if humanity_details[:is_human] && @post.save
        redirect_to @post, notice: 'Post was successfully created.'
      else
        render :new
      end
    end

There are two mandatory arguments for human? method:

  • token - token valid for your site
  • action - the action name for this request (the gem checks if it is the same as the name used with the token, otherwise a hacker could replace it on frontend to some another action used, but with lower score requirement and thus pass the verification)

You can verify recaptcha without using these arguments:

  • minimum_score - defaults to value set in the initializer (reCAPTCHA recommends using 0.5 as default)
  • model - defaults to nil which will result in not adding an error to model; any custom failure handling is applicable here

like this:

  NewGoogleRecaptcha.human?(params[:new_google_recaptcha_token], "checkout")

Saving humanity score from Google in your model

get_humanity_detailed method acts like human? method, the only difference is that it returns following hash with three key-value pairs:

  • is_human - whether actor is a human or not (same as result of human? method)
  • score - actual humanity score from recaptcha response
  • model - model which you trying to save

It could be handy if you want to store score in db or put it into logs or smth else. Real example is above in the code samples.

Add to your navigation links data-turbolinks="false" to make it works with turbolinks.

Installation

gem 'new_google_recaptcha'

And then execute:

$ bundle

And then run:

$ rails generate new_google_recaptcha initializer

And edit new_google_recaptcha.rb and enter your site_key and secret_key.

API

NewGoogleRecaptcha.human?(token, model) or NewGoogleRecaptcha.get_humanity_detailed(token, model) in contoller

  • token is received from google, must be sent to backend
  • model optional parameter. if you want to add error to model.

<%= include_recaptcha_js %> in layout (by using yield)

Include Google Recaptcha v3 JS into your Rails app. In head, right before </head>.

<%= recaptcha_action(action_name) %> in view

Action where recaptcha action was executed. Actions could be viewed in Admin console. More docs: https://developers.google.com/recaptcha/docs/v3. Action name could be "comments", "checkout", etc. Put any name and check scores in console.

How to add to the Devise

Generate Devise controllers and views, and edit "create" method.

class Users::RegistrationsController < Devise::RegistrationsController
...
  def create
    build_resource(sign_up_params)

    NewGoogleRecaptcha.human?(
      params[:new_google_recaptcha_token],
      "user",
      NewGoogleRecaptcha.minimum_score,
      resource) && resource.save

    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

How to use in test or specs

At the end of the spec/rails_helper.rb put:

module NewGoogleRecaptcha
  def self.human?(*attrs)
    true
  end
end

Tests are located in specs folder and test/dummy/tests folder.

I18n support

reCAPTCHA passes one types of error explanation to a linked model. It will use the I18n gem to translate the default error message if I18n is available. To customize the messages to your locale, add these keys to your I18n backend:

new_google_recaptcha.errors.verification_human error message displayed when it is something like a robot, or a suspicious action

Also you can translate API response errors to human friendly by adding translations to the locale (config/locales/en.yml):

en:
  new_google_recaptcha:
    errors:
      verification_human: 'Fail'

Badge position

NewGoogleRecaptcha allows you to render badge in different positions

    <%= include_recaptcha_js badge: "bottomleft" %>

Three of existing badge values are bottomright, bottomleft and inline. 'inline' lets you position it with CSS.

TODO

  • check everything works with turbolinks
  • allow custom ID for input
  • more tests
  • handle exceptions with timeouts, json is not parsed
  • add support for non-Rails apps
  • add support for older Rails (should be easy since code is very simple)

Contributors

You are welcome to contribute.

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

rails_db

Rails Database Viewer and SQL Query Runner
JavaScript
1,447
star
2

active_storage_validations

Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, max: 3 }, aspect_ratio: :landscape, dimension: { width: { in: 800..1600 }
Ruby
959
star
3

rails_performance

Monitor performance of you Rails applications (self-hosted and free)
Ruby
793
star
4

any_login

Easy way to login as any user in system
Ruby
373
star
5

log_analyzer

Rails logs analyzer (see how fast your views are rendering)
Ruby
349
star
6

rails_pdf

A reliable way to generate PDF of any complexity in Ruby on Rails apps
HTML
175
star
7

fake_api

The fastest way to prototype API in your Rails application
Ruby
142
star
8

execution_time

How fast is your code? See it directly in Rails console.
Ruby
111
star
9

benchmark_methods

Benchmark and measure execution time your Ruby methods without an additional code changes
Ruby
89
star
10

transactify

Wrap your methods in DB Transactions
Ruby
55
star
11

sql_view

Rails SQL Views made easy ;)
Ruby
49
star
12

sweet_staging

Access your Rails console, see logs, execute rake commands directly from the browser. Great addition to your Staging ENV.
JavaScript
46
star
13

execute_sql

Execute SQL inside Rails console, or app itself
Ruby
41
star
14

cache_with_locale

Easy wait to do view caching with automatically added "locale" value to the cached key.
Ruby
37
star
15

avatarro

Generate google-style avatars in your application
Ruby
37
star
16

awesome_back_url

Redirect the user to the proper "back" page
Ruby
33
star
17

new_ckeditor

Ruby on Rails + CKEditor 5
Ruby
31
star
18

records_count

See in development logs how many records your queries returns. It can help with solving performance issues.
Ruby
31
star
19

amazon_static_site

Static website using https with your own domain name using Amazon S3 and Cloudflare for FREE
Ruby
29
star
20

omg_image

Generate PNG previews for HTML snippets (html/css/js). Any complexity.
Ruby
28
star
21

wrapped_print

Easy print debug information to your console in Ruby/Rails app.
Ruby
23
star
22

calculate_in_group

Group Active Record by ranges or set of values with a single SQL query.
Ruby
22
star
23

embed_view

Embed ERB files inside another ERB files for faster performance (5-20% BOOST!!!)
HTML
21
star
24

rails_time_travel

HTML
19
star
25

sabotage

Coding & debugging must be fun. Make life a bit harder for your colleagues :)
Ruby
18
star
26

mechanical

All models in a single table, new attributes without migrations. Works like regular AR model
Ruby
17
star
27

secrett11tto

Simple way to protect your content from copy-pasting
Ruby
15
star
28

rails_live

Ruby
15
star
29

mini-guard

Ruby
14
star
30

railsjazz.com

Rails Jazz (personal web site)
JavaScript
14
star
31

sidekiq_log_analyzer

SidekiqLogAnalyser gem allows to see summary of your sidekiq workers (based on log file).
Ruby
13
star
32

hasharay_ext

Painless work with complex Ruby hashes/arrays.
Ruby
13
star
33

active_storage_silent_logs

The idea of this gem is to hide as much as possible Active Storage logs from console so you can see only important information and requests
Ruby
13
star
34

rails_cached_method

Simple way to cache results of methods.
Ruby
11
star
35

with_record

Returns relations/association for soft deleted records in DB
Ruby
10
star
36

rrr

Run recent rspec files only (the only recently modified).
Ruby
9
star
37

font_awesome_file_icons

Ruby
4
star
38

unwhere

Ruby
4
star
39

travel_and_talk

JavaScript
3
star
40

lazy_mobile_tester

Rails Lazy Mobile Tester
Ruby
3
star
41

serpjazz

SERP keywords tracking
JavaScript
3
star
42

jeanappv2

JavaScript
2
star
43

mega-simple-authorization

mega simple authorization plugin for RoR
Ruby
2
star
44

tv

eb5 tv
JavaScript
2
star
45

spring_rspec_commands_addon

rails+spring+rspec = friends :)
Ruby
2
star
46

layouts_from_db_sample

Allow store layouts to DB (Sample)
2
star
47

CheaperDrinker

CheaperDrinker web site
JavaScript
2
star
48

any_login_test

AnyLogin gem test application
Ruby
2
star
49

tell_my_env

Ruby
2
star
50

slim_erb_backport

Slim 4+ and ERB friends again :)
Ruby
2
star
51

VerySimple

1
star
52

ShareT

online translations
JavaScript
1
star
53

test-ec2

test-ec2
1
star
54

sa1

1
star
55

better_tempfile

Ruby
1
star
56

just_for_fun

Do you want to call 42.to_user, [42, 43, 44].to_users? Try this gem :)
Ruby
1
star
57

tophouse.com.ua

JavaScript
1
star
58

ar_enumerations_test_application

ActiveRecord enumeration field type - test application
Ruby
1
star
59

capistranotest

1
star
60

zip_and_phone

Zips & Phones
Ruby
1
star
61

portfolio

1
star
62

tdemo

tdemo
Ruby
1
star
63

cisarska_and_frankivska

Cisarska & Frankivska
JavaScript
1
star
64

seminars

JavaScript
1
star
65

deprecations_collector

Save all Rails deprecation in log file for future investigation
Ruby
1
star
66

rails_logs

Ruby
1
star