recaptcha 2.3.0 → 5.8.1

Sign up to get free protection for your applications and to get access to all the features.
data/README.md CHANGED
@@ -1,4 +1,6 @@
1
+
1
2
  # reCAPTCHA
3
+ [![Gem Version](https://badge.fury.io/rb/recaptcha.svg)](https://badge.fury.io/rb/recaptcha)
2
4
 
3
5
  Author: Jason L Perry (http://ambethia.com)<br/>
4
6
  Copyright: Copyright (c) 2007-2013 Jason L Perry<br/>
@@ -6,42 +8,87 @@ License: [MIT](http://creativecommons.org/licenses/MIT/)<br/>
6
8
  Info: https://github.com/ambethia/recaptcha<br/>
7
9
  Bugs: https://github.com/ambethia/recaptcha/issues<br/>
8
10
 
9
- This plugin adds helpers for the [reCAPTCHA API](https://www.google.com/recaptcha). In your
10
- views you can use the `recaptcha_tags` method to embed the needed javascript,
11
- and you can validate in your controllers with `verify_recaptcha` or `verify_recaptcha!`,
12
- which throws an error on failiure.
11
+ This gem provides helper methods for the [reCAPTCHA API](https://www.google.com/recaptcha). In your
12
+ views you can use the `recaptcha_tags` method to embed the needed javascript, and you can validate
13
+ in your controllers with `verify_recaptcha` or `verify_recaptcha!`, which raises an error on
14
+ failure.
13
15
 
14
- ## Rails Installation
15
16
 
16
- [obtain a reCAPTCHA API key](https://www.google.com/recaptcha/admin).
17
+ # Table of Contents
18
+ 1. [Obtaining a key](#obtaining-a-key)
19
+ 2. [Rails Installation](#rails-installation)
20
+ 3. [Sinatra / Rack / Ruby Installation](#sinatra--rack--ruby-installation)
21
+ 4. [reCAPTCHA V2 API & Usage](#recaptcha-v2-api-and-usage)
22
+ - [`recaptcha_tags`](#recaptcha_tags)
23
+ - [`verify_recaptcha`](#verify_recaptcha)
24
+ - [`invisible_recaptcha_tags`](#invisible_recaptcha_tags)
25
+ 5. [reCAPTCHA V3 API & Usage](#recaptcha-v3-api-and-usage)
26
+ - [`recaptcha_v3`](#recaptcha_v3)
27
+ - [`verify_recaptcha` (use with v3)](#verify_recaptcha-use-with-v3)
28
+ - [`recaptcha_reply`](#recaptcha_reply)
29
+ 6. [I18n Support](#i18n-support)
30
+ 7. [Testing](#testing)
31
+ 8. [Alternative API Key Setup](#alternative-api-key-setup)
32
+
33
+ ## Obtaining a key
34
+
35
+ Go to the [reCAPTCHA admin console](https://www.google.com/recaptcha/admin) to obtain a reCAPTCHA API key.
36
+
37
+ The reCAPTCHA type(s) that you choose for your key will determine which methods to use below.
38
+
39
+ | reCAPTCHA type | Methods to use | Description |
40
+ |----------------------------------------------|----------------|-------------|
41
+ | v3 | [`recaptcha_v3`](#recaptcha_v3) | Verify requests with a [score](https://developers.google.com/recaptcha/docs/v3#score)
42
+ | v2 Checkbox<br/>("I'm not a robot" Checkbox) | [`recaptcha_tags`](#recaptcha_tags) | Validate requests with the "I'm not a robot" checkbox |
43
+ | v2 Invisible<br/>(Invisible reCAPTCHA badge) | [`invisible_recaptcha_tags`](#invisible_recaptcha_tags) | Validate requests in the background |
44
+
45
+ Note: You can _only_ use methods that match your key's type. You cannot use v2 methods with a v3
46
+ key or use `recaptcha_tags` with a v2 Invisible key, for example. Otherwise you will get an
47
+ error like "Invalid key type" or "This site key is not enabled for the invisible captcha."
17
48
 
18
- ```Ruby
19
- gem "recaptcha", require: "recaptcha/rails"
49
+ Note: Enter `localhost` or `127.0.0.1` as the domain if using in development with `localhost:3000`.
50
+
51
+ ## Rails Installation
52
+
53
+ ```ruby
54
+ gem "recaptcha"
20
55
  ```
21
56
 
22
- Keep keys out of the code base with environment variables.<br/>
23
- Set in production and locally use [dotenv](https://github.com/bkeepers/dotenv), make sure to add it above recaptcha.
57
+ You can keep keys out of the code base with environment variables or with Rails [secrets](https://api.rubyonrails.org/classes/Rails/Application.html#method-i-secrets).<br/>
24
58
 
25
- Otherwise see [Alternative API key setup](#alternative-api-key-setup).
59
+ In development, you can use the [dotenv](https://github.com/bkeepers/dotenv) gem. (Make sure to add it above `gem 'recaptcha'`.)
26
60
 
61
+ See [Alternative API key setup](#alternative-api-key-setup) for more ways to configure or override
62
+ keys. See also the
63
+ [Configuration](https://www.rubydoc.info/github/ambethia/recaptcha/master/Recaptcha/Configuration)
64
+ documentation.
65
+
66
+ ```shell
67
+ export RECAPTCHA_SITE_KEY = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
68
+ export RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
27
69
  ```
28
- export RECAPTCHA_PUBLIC_KEY = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
29
- export RECAPTCHA_PRIVATE_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
70
+
71
+ If you have an Enterprise API key:
72
+
73
+ ```shell
74
+ export RECAPTCHA_ENTERPRISE = 'true'
75
+ export RECAPTCHA_ENTERPRISE_API_KEY = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA'
76
+ export RECAPTCHA_ENTERPRISE_PROJECT_ID = 'my-project'
30
77
  ```
31
78
 
32
- Add `recaptcha_tags` to the forms you want to protect.
79
+ Add `recaptcha_tags` to the forms you want to protect:
33
80
 
34
- ```Erb
81
+ ```erb
35
82
  <%= form_for @foo do |f| %>
36
- # ... other tags
83
+ #
37
84
  <%= recaptcha_tags %>
38
- # ... other tags
85
+ #
39
86
  <% end %>
40
87
  ```
41
88
 
42
- And, add `verify_recaptcha` logic to each form action that you've protected.
89
+ Then, add `verify_recaptcha` logic to each form action that you've protected:
43
90
 
44
- ```Ruby
91
+ ```ruby
45
92
  # app/controllers/users_controller.rb
46
93
  @user = User.new(params[:user].permit(:name))
47
94
  if verify_recaptcha(model: @user) && @user.save
@@ -50,6 +97,7 @@ else
50
97
  render 'new'
51
98
  end
52
99
  ```
100
+ Please note that this setup uses [`reCAPTCHA_v2`](#recaptcha-v2-api-and-usage). For a `recaptcha_v3` use, please refer to [`reCAPTCHA_v3 setup`](#examples).
53
101
 
54
102
  ## Sinatra / Rack / Ruby installation
55
103
 
@@ -57,68 +105,407 @@ See [sinatra demo](/demo/sinatra) for details.
57
105
 
58
106
  - add `gem 'recaptcha'` to `Gemfile`
59
107
  - set env variables
60
- - `include Recaptcha::ClientHelper` where you need `recaptcha_tags`
61
- - `include Recaptcha::Verify` where you need `verify_recaptcha`
108
+ - `include Recaptcha::Adapters::ViewMethods` where you need `recaptcha_tags`
109
+ - `include Recaptcha::Adapters::ControllerMethods` where you need `verify_recaptcha`
62
110
 
63
- ## recaptcha_tags
64
111
 
65
- Some of the options available:
112
+ ## reCAPTCHA v2 API and Usage
113
+
114
+ ### `recaptcha_tags`
115
+
116
+ Use this when your key's reCAPTCHA type is "v2 Checkbox".
117
+
118
+ The following options are available:
119
+
120
+ | Option | Description |
121
+ |---------------------|-------------|
122
+ | `:theme` | Specify the theme to be used per the API. Available options: `dark` and `light`. (default: `light`) |
123
+ | `:ajax` | Render the dynamic AJAX captcha per the API. (default: `false`) |
124
+ | `:site_key` | Override site API key from configuration |
125
+ | `:error` | Override the error code returned from the reCAPTCHA API (default: `nil`) |
126
+ | `:size` | Specify a size (default: `nil`) |
127
+ | `:nonce` | Optional. Sets nonce attribute for script. Can be generated via `SecureRandom.base64(32)`. (default: `nil`) |
128
+ | `:id` | Specify an html id attribute (default: `nil`) |
129
+ | `:callback` | Optional. Name of success callback function, executed when the user submits a successful response |
130
+ | `:expired_callback` | Optional. Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify. |
131
+ | `:error_callback` | Optional. Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity) |
132
+ | `:noscript` | Include `<noscript>` content (default: `true`)|
66
133
 
67
- | Option | Description |
68
- |-------------|-------------|
69
- | :ssl | Uses secure http for captcha widget (default `false`, but can be changed by setting `config.use_ssl_by_default`)|
70
- | :noscript | Include <noscript> content (default `true`)|
71
- | :display | Takes a hash containing the `theme` and `tabindex` options per the API. (default `nil`), options: 'red', 'white', 'blackglass', 'clean', 'custom'|
72
- | :ajax | Render the dynamic AJAX captcha per the API. (default `false`)|
73
- | :public_key | Override public API key |
74
- | :error | Override the error code returned from the reCAPTCHA API (default `nil`)|
75
- | :size | Specify a size (default `nil`)|
76
- | :hl | Optional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (See [language codes](https://developers.google.com/recaptcha/docs/language)) |
134
+ [JavaScript resource (api.js) parameters](https://developers.google.com/recaptcha/docs/invisible#js_param):
135
+
136
+ | Option | Description |
137
+ |---------------------|-------------|
138
+ | `:onload` | Optional. The name of your callback function to be executed once all the dependencies have loaded. (See [explicit rendering](https://developers.google.com/recaptcha/docs/display#explicit_render)) |
139
+ | `:render` | Optional. Whether to render the widget explicitly. Defaults to `onload`, which will render the widget in the first g-recaptcha tag it finds. (See [explicit rendering](https://developers.google.com/recaptcha/docs/display#explicit_render)) |
140
+ | `:hl` | Optional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (See [language codes](https://developers.google.com/recaptcha/docs/language)) |
141
+ | `:script` | Alias for `:external_script`. If you do not need to add a script tag by helper you can set the option to `false`. It's necessary when you add a script tag manualy (default: `true`). |
142
+ | `:external_script` | Set to `false` to avoid including a script tag for the external `api.js` resource. Useful when including multiple `recaptcha_tags` on the same page. |
143
+ | `:script_async` | Set to `false` to load the external `api.js` resource synchronously. (default: `true`) |
144
+ | `:script_defer` | Set to `true` to defer loading of external `api.js` until HTML documen has been parsed. (default: `true`) |
145
+
146
+ Any unrecognized options will be added as attributes on the generated tag.
77
147
 
78
148
  You can also override the html attributes for the sizes of the generated `textarea` and `iframe`
79
- elements, if CSS isn't your thing. Inspect the source of `recaptcha_tags` to see these options.
149
+ elements, if CSS isn't your thing. Inspect the [source of `recaptcha_tags`](https://github.com/ambethia/recaptcha/blob/master/lib/recaptcha/helpers.rb)
150
+ to see these options.
151
+
152
+ Note that you cannot submit/verify the same response token more than once or you will get a
153
+ `timeout-or-duplicate` error code. If you need reset the captcha and generate a new response token,
154
+ then you need to call `grecaptcha.reset()`.
80
155
 
81
- ## verify_recaptcha
156
+ ### `verify_recaptcha`
82
157
 
83
- This method returns `true` or `false` after processing the parameters from the reCAPTCHA widget. Why
84
- isn't this a model validation? Because that violates MVC. You can use it like this, or how ever you
85
- like. Passing in the ActiveRecord object is optional, if you do--and the captcha fails to verify--an
86
- error will be added to the object for you to use.
158
+ This method returns `true` or `false` after processing the response token from the reCAPTCHA widget.
159
+ This is usually called from your controller, as seen [above](#rails-installation).
160
+
161
+ Passing in the ActiveRecord object via `model: object` is optional. If you pass a `model`—and the
162
+ captcha fails to verify—an error will be added to the object for you to use (available as
163
+ `object.errors`).
164
+
165
+ Why isn't this a model validation? Because that violates MVC. You can use it like this, or how ever
166
+ you like.
87
167
 
88
168
  Some of the options available:
89
169
 
90
- | Option | Description |
91
- |--------------|-------------|
92
- | :model | Model to set errors.
93
- | :attribute | Model attribute to receive errors. (default :base)
94
- | :message | Custom error message.
95
- | :private_key | Override private API key.
96
- | :timeout | The number of seconds to wait for reCAPTCHA servers before give up. (default `3`)
97
- | :response | Custom response parameter. (default: params['g-recaptcha-response'])
98
- | :hostname | Expected hostname or a callable that validates the hostname, see [domain validation](https://developers.google.com/recaptcha/docs/domain_validation) and [hostname](https://developers.google.com/recaptcha/docs/verify#api-response) docs. (default: `nil`, but can be changed by setting `config.hostname`)
170
+ | Option | Description |
171
+ |---------------------------|-------------|
172
+ | `:model` | Model to set errors.
173
+ | `:attribute` | Model attribute to receive errors. (default: `:base`)
174
+ | `:message` | Custom error message.
175
+ | `:secret_key` | Override the secret API key from the configuration.
176
+ | `:enterprise_api_key` | Override the Enterprise API key from the configuration.
177
+ | `:enterprise_project_id ` | Override the Enterprise project ID from the configuration.
178
+ | `:timeout` | The number of seconds to wait for reCAPTCHA servers before give up. (default: `3`)
179
+ | `:response` | Custom response parameter. (default: `params['g-recaptcha-response-data']`)
180
+ | `:hostname` | Expected hostname or a callable that validates the hostname, see [domain validation](https://developers.google.com/recaptcha/docs/domain_validation) and [hostname](https://developers.google.com/recaptcha/docs/verify#api-response) docs. (default: `nil`, but can be changed by setting `config.hostname`)
181
+ | `:env` | Current environment. The request to verify will be skipped if the environment is specified in configuration under `skip_verify_env`
99
182
 
100
- ## I18n support
101
- reCAPTCHA passes two types of error explanation to a linked model. It will use the I18n gem
102
- to translate the default error message if I18n is available. To customize the messages to your locale,
103
- add these keys to your I18n backend:
104
183
 
105
- `recaptcha.errors.verification_failed` error message displayed if the captcha words didn't match
106
- `recaptcha.errors.recaptcha_unreachable` displayed if a timeout error occured while attempting to verify the captcha
184
+ ### `invisible_recaptcha_tags`
185
+
186
+ Use this when your key's reCAPTCHA type is "v2 Invisible".
187
+
188
+ For more information, refer to: [Invisible reCAPTCHA](https://developers.google.com/recaptcha/docs/invisible).
189
+
190
+ This is similar to `recaptcha_tags`, with the following additional options that are only available
191
+ on `invisible_recaptcha_tags`:
192
+
193
+ | Option | Description |
194
+ |---------------------|-------------|
195
+ | `:ui` | The type of UI to render for this "invisible" widget. (default: `:button`)<br/>`:button`: Renders a `<button type="submit">` tag with `options[:text]` as the button text.<br/>`:invisible`: Renders a `<div>` tag.<br/>`:input`: Renders a `<input type="submit">` tag with `options[:text]` as the button text. |
196
+ | `:text` | The text to show for the button. (default: `"Submit"`)
197
+ | `:inline_script` | If you do not need this helper to add an inline script tag, you can set the option to `false` (default: `true`).
198
+
199
+ It also accepts most of the options that `recaptcha_tags` accepts, including the following:
200
+
201
+ | Option | Description |
202
+ |---------------------|-------------|
203
+ | `:site_key` | Override site API key from configuration |
204
+ | `:nonce` | Optional. Sets nonce attribute for script tag. Can be generated via `SecureRandom.base64(32)`. (default: `nil`) |
205
+ | `:id` | Specify an html id attribute (default: `nil`) |
206
+ | `:script` | Same as setting both `:inline_script` and `:external_script`. If you only need one or the other, use `:inline_script` and `:external_script` instead. |
207
+ | `:callback` | Optional. Name of success callback function, executed when the user submits a successful response |
208
+ | `:expired_callback` | Optional. Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify. |
209
+ | `:error_callback` | Optional. Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity) |
210
+
211
+ [JavaScript resource (api.js) parameters](https://developers.google.com/recaptcha/docs/invisible#js_param):
212
+
213
+ | Option | Description |
214
+ |---------------------|-------------|
215
+ | `:onload` | Optional. The name of your callback function to be executed once all the dependencies have loaded. (See [explicit rendering](https://developers.google.com/recaptcha/docs/display#explicit_render)) |
216
+ | `:render` | Optional. Whether to render the widget explicitly. Defaults to `onload`, which will render the widget in the first g-recaptcha tag it finds. (See [explicit rendering](https://developers.google.com/recaptcha/docs/display#explicit_render)) |
217
+ | `:hl` | Optional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (See [language codes](https://developers.google.com/recaptcha/docs/language)) |
218
+ | `:external_script` | Set to `false` to avoid including a script tag for the external `api.js` resource. Useful when including multiple `recaptcha_tags` on the same page. |
219
+ | `:script_async` | Set to `false` to load the external `api.js` resource synchronously. (default: `true`) |
220
+ | `:script_defer` | Set to `false` to defer loading of external `api.js` until HTML documen has been parsed. (default: `true`) |
221
+
222
+ ### With a single form on a page
223
+
224
+ 1. The `invisible_recaptcha_tags` generates a submit button for you.
225
+
226
+ ```erb
227
+ <%= form_for @foo do |f| %>
228
+ # ... other tags
229
+ <%= invisible_recaptcha_tags text: 'Submit form' %>
230
+ <% end %>
231
+ ```
232
+
233
+ Then, add `verify_recaptcha` to your controller as seen [above](#rails-installation).
234
+
235
+ ### With multiple forms on a page
236
+
237
+ 1. You will need a custom callback function, which is called after verification with Google's reCAPTCHA service. This callback function must submit the form. Optionally, `invisible_recaptcha_tags` currently implements a JS function called `invisibleRecaptchaSubmit` that is called when no `callback` is passed. Should you wish to override `invisibleRecaptchaSubmit`, you will need to use `invisible_recaptcha_tags script: false`, see lib/recaptcha/client_helper.rb for details.
238
+ 2. The `invisible_recaptcha_tags` generates a submit button for you.
239
+
240
+ ```erb
241
+ <%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f| %>
242
+ # ... other tags
243
+ <%= invisible_recaptcha_tags callback: 'submitInvisibleRecaptchaForm', text: 'Submit form' %>
244
+ <% end %>
245
+ ```
246
+
247
+ ```javascript
248
+ // app/assets/javascripts/application.js
249
+ var submitInvisibleRecaptchaForm = function () {
250
+ document.getElementById("invisible-recaptcha-form").submit();
251
+ };
252
+ ```
253
+
254
+ Finally, add `verify_recaptcha` to your controller as seen [above](#rails-installation).
255
+
256
+ ### Programmatically invoke
107
257
 
108
- Also you can translate API response errors to human friendly by adding translations to the locale (`config/locales/en.yml`):
258
+ 1. Specify `ui` option
109
259
 
110
- ```Yaml
260
+ ```erb
261
+ <%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f| %>
262
+ # ... other tags
263
+ <button type="button" id="submit-btn">
264
+ Submit
265
+ </button>
266
+ <%= invisible_recaptcha_tags ui: :invisible, callback: 'submitInvisibleRecaptchaForm' %>
267
+ <% end %>
268
+ ```
269
+
270
+ ```javascript
271
+ // app/assets/javascripts/application.js
272
+ document.getElementById('submit-btn').addEventListener('click', function (e) {
273
+ // do some validation
274
+ if(isValid) {
275
+ // call reCAPTCHA check
276
+ grecaptcha.execute();
277
+ }
278
+ });
279
+
280
+ var submitInvisibleRecaptchaForm = function () {
281
+ document.getElementById("invisible-recaptcha-form").submit();
282
+ };
283
+ ```
284
+
285
+
286
+ ## reCAPTCHA v3 API and Usage
287
+
288
+ The main differences from v2 are:
289
+ 1. you must specify an [action](https://developers.google.com/recaptcha/docs/v3#actions) in both frontend and backend
290
+ 1. you can choose the minimum score required for you to consider the verification a success
291
+ (consider the user a human and not a robot)
292
+ 1. reCAPTCHA v3 is invisible (except for the reCAPTCHA badge) and will never interrupt your users;
293
+ you have to choose which scores are considered an acceptable risk, and choose what to do (require
294
+ two-factor authentication, show a v3 challenge, etc.) if the score falls below the threshold you
295
+ choose
296
+
297
+ For more information, refer to the [v3 documentation](https://developers.google.com/recaptcha/docs/v3).
298
+
299
+ ### Examples
300
+
301
+ With v3, you can let all users log in without any intervention at all if their score is above some
302
+ threshold, and only show a v2 checkbox recaptcha challenge (fall back to v2) if it is below the
303
+ threshold:
304
+
305
+ ```erb
306
+
307
+ <% if @show_checkbox_recaptcha %>
308
+ <%= recaptcha_tags %>
309
+ <% else %>
310
+ <%= recaptcha_v3(action: 'login', site_key: ENV['RECAPTCHA_SITE_KEY_V3']) %>
311
+ <% end %>
312
+
313
+ ```
314
+
315
+ ```ruby
316
+ # app/controllers/sessions_controller.rb
317
+ def create
318
+ success = verify_recaptcha(action: 'login', minimum_score: 0.5, secret_key: ENV['RECAPTCHA_SECRET_KEY_V3'])
319
+ checkbox_success = verify_recaptcha unless success
320
+ if success || checkbox_success
321
+ # Perform action
322
+ else
323
+ if !success
324
+ @show_checkbox_recaptcha = true
325
+ end
326
+ render 'new'
327
+ end
328
+ end
329
+ ```
330
+
331
+ (You can also find this [example](demo/rails/app/controllers/v3_captchas_controller.rb) in the demo app.)
332
+
333
+ Another example:
334
+
335
+ ```erb
336
+ <%= form_for @user do |f| %>
337
+
338
+ <%= recaptcha_v3(action: 'registration') %>
339
+
340
+ <% end %>
341
+ ```
342
+
343
+ ```ruby
344
+ # app/controllers/users_controller.rb
345
+ def create
346
+ @user = User.new(params[:user].permit(:name))
347
+ recaptcha_valid = verify_recaptcha(model: @user, action: 'registration')
348
+ if recaptcha_valid
349
+ if @user.save
350
+ redirect_to @user
351
+ else
352
+ render 'new'
353
+ end
354
+ else
355
+ # Score is below threshold, so user may be a bot. Show a challenge, require multi-factor
356
+ # authentication, or do something else.
357
+ render 'new'
358
+ end
359
+ end
360
+ ```
361
+
362
+
363
+ ### `recaptcha_v3`
364
+
365
+ Adds an inline script tag that calls `grecaptcha.execute` for the given `site_key` and `action` and
366
+ calls the `callback` with the resulting response token. You need to verify this token with
367
+ [`verify_recaptcha`](#verify_recaptcha-use-with-v3) in your controller in order to get the
368
+ [score](https://developers.google.com/recaptcha/docs/v3#score).
369
+
370
+ By default, this inserts a hidden `<input type="hidden" class="g-recaptcha-response">` tag. The
371
+ value of this input will automatically be set to the response token (by the default callback
372
+ function). This lets you include `recaptcha_v3` within a `<form>` tag and have it automatically
373
+ submit the token as part of the form submission.
374
+
375
+ Note: reCAPTCHA actually already adds its own hidden tag, like `<textarea
376
+ id="g-recaptcha-response-data-100000" name="g-recaptcha-response-data" class="g-recaptcha-response">`,
377
+ immediately ater the reCAPTCHA badge in the bottom right of the page — but since it is not inside of
378
+ any `<form>` element, and since it already passes the token to the callback, this hidden `textarea`
379
+ isn't helpful to us.
380
+
381
+ If you need to submit the response token to the server in a different way than via a regular form
382
+ submit, such as via [Ajax](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) or [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API),
383
+ then you can either:
384
+ 1. just extract the token out of the hidden `<input>` or `<textarea>` (both of which will have a
385
+ predictable name/id), like `document.getElementById('g-recaptcha-response-data-my-action').value`, or
386
+ 2. write and specify a custom `callback` function. You may also want to pass `element: false` if you
387
+ don't have a use for the hidden input element.
388
+
389
+ Note that you cannot submit/verify the same response token more than once or you
390
+ will get a `timeout-or-duplicate` error code. If you need reset the captcha and
391
+ generate a new response token, then you need to call `grecaptcha.execute(…)` or
392
+ `grecaptcha.enterprise.execute(…)` again. This helper provides a JavaScript
393
+ method (for each action) named `executeRecaptchaFor{action}` to make this
394
+ easier. That is the same method that is invoked immediately. It simply calls
395
+ `grecaptcha.execute` or `grecaptcha.enterprise.execute` again and then calls the
396
+ `callback` function with the response token.
397
+
398
+ You will also get a `timeout-or-duplicate` error if too much time has passed between getting the
399
+ response token and verifying it. This can easily happen with large forms that take the user a couple
400
+ minutes to complete. Unlike v2, where you can use the `expired-callback` to be notified when the
401
+ response expires, v3 appears to provide no such callback. See also
402
+ [1](https://github.com/google/recaptcha/issues/281) and
403
+ [2](https://stackoverflow.com/questions/54437745/recaptcha-v3-how-to-deal-with-expired-token-after-idle).
404
+
405
+ To deal with this, it is recommended to call the "execute" in your form's submit handler (or
406
+ immediately before sending to the server to verify if not using a form) rather than using the
407
+ response token that gets generated when the page first loads. The `executeRecaptchaFor{action}`
408
+ function mentioned above can be used if you want it to invoke a callback, or the
409
+ `executeRecaptchaFor{action}Async` variant if you want a `Promise` that you can `await`. See
410
+ [demo/rails/app/views/v3_captchas/index.html.erb](demo/rails/app/views/v3_captchas/index.html.erb)
411
+ for an example of this.
412
+
413
+ This helper is similar to the [`recaptcha_tags`](#recaptcha_tags)/[`invisible_recaptcha_tags`](#invisible_recaptcha_tags) helpers
414
+ but only accepts the following options:
415
+
416
+ | Option | Description |
417
+ |---------------------|-------------|
418
+ | `:site_key` | Override site API key |
419
+ | `:action` | The name of the [reCAPTCHA action](https://developers.google.com/recaptcha/docs/v3#actions). Actions may only contain alphanumeric characters and slashes, and must not be user-specific. |
420
+ | `:nonce` | Optional. Sets nonce attribute for script. Can be generated via `SecureRandom.base64(32)`. (default: `nil`) |
421
+ | `:callback` | Name of callback function to call with the token. When `element` is `:input`, this defaults to a function named `setInputWithRecaptchaResponseTokenFor#{sanitize_action(action)}` that sets the value of the hidden input to the token. |
422
+ | `:id` | Specify a unique `id` attribute for the `<input>` element if using `element: :input`. (default: `"g-recaptcha-response-data-"` + `action`) |
423
+ | `:name` | Specify a unique `name` attribute for the `<input>` element if using `element: :input`. (default: `g-recaptcha-response-data[action]`) |
424
+ | `:script` | Same as setting both `:inline_script` and `:external_script`. (default: `true`). |
425
+ | `:inline_script` | If `true`, adds an inline script tag that calls `grecaptcha.execute` for the given `site_key` and `action` and calls the `callback` with the resulting response token. Pass `false` if you want to handle calling `grecaptcha.execute` yourself. (default: `true`) |
426
+ | `:element` | The element to render, if any (default: `:input`)<br/>`:input`: Renders a hidden `<input type="hidden">` tag. The value of this will be set to the response token by the default `setInputWithRecaptchaResponseTokenFor{action}` callback.<br/>`false`: Doesn't render any tag. You'll have to add a custom callback that does something with the token. |
427
+ | `:turbolinks` | If `true`, calls the js function which executes reCAPTCHA after all the dependencies have been loaded. This cannot be used with the js param `:onload`. This makes reCAPTCHAv3 usable with turbolinks. |
428
+
429
+ [JavaScript resource (api.js) parameters](https://developers.google.com/recaptcha/docs/invisible#js_param):
430
+
431
+ | Option | Description |
432
+ |---------------------|-------------|
433
+ | `:onload` | Optional. The name of your callback function to be executed once all the dependencies have loaded. (See [explicit rendering](https://developers.google.com/recaptcha/docs/display#explicit_render))|
434
+ | `:external_script` | Set to `false` to avoid including a script tag for the external `api.js` resource. Useful when including multiple `recaptcha_tags` on the same page.
435
+ | `:script_async` | Set to `true` to load the external `api.js` resource asynchronously. (default: `false`) |
436
+ | `:script_defer` | Set to `true` to defer loading of external `api.js` until HTML documen has been parsed. (default: `false`) |
437
+
438
+ If using `element: :input`, any unrecognized options will be added as attributes on the generated
439
+ `<input>` element.
440
+
441
+ ### `verify_recaptcha` (use with v3)
442
+
443
+ This works the same as for v2, except that you may pass an `action` and `minimum_score` if you wish
444
+ to validate that the action matches or that the score is above the given threshold, respectively.
445
+
446
+ ```ruby
447
+ result = verify_recaptcha(action: 'action/name')
448
+ ```
449
+
450
+ | Option | Description |
451
+ |------------------|-------------|
452
+ | `:action` | The name of the [reCAPTCHA action](https://developers.google.com/recaptcha/docs/v3#actions) that we are verifying. Set to `false` or `nil` to skip verifying that the action matches.
453
+ | `:minimum_score` | Provide a threshold to meet or exceed. Threshold should be a float between 0 and 1 which will be tested as `score >= minimum_score`. (Default: `nil`) |
454
+
455
+ ### Multiple actions on the same page
456
+
457
+ According to https://developers.google.com/recaptcha/docs/v3#placement,
458
+
459
+ > Note: You can execute reCAPTCHA as many times as you'd like with different actions on the same page.
460
+
461
+ You will need to verify each action individually with a separate call to `verify_recaptcha`.
462
+
463
+ ```ruby
464
+ result_a = verify_recaptcha(action: 'a')
465
+ result_b = verify_recaptcha(action: 'b')
466
+ ```
467
+
468
+ Because the response tokens for multiple actions may be submitted together in the same request, they
469
+ are passed as a hash under `params['g-recaptcha-response-data']` with the action as the key.
470
+
471
+ It is recommended to pass `external_script: false` on all but one of the calls to
472
+ `recaptcha` since you only need to include the script tag once for a given `site_key`.
473
+
474
+ ## `recaptcha_reply`
475
+
476
+ After `verify_recaptcha` has been called, you can call `recaptcha_reply` to get the raw reply from recaptcha. This can allow you to get the exact score returned by recaptcha should you need it.
477
+
478
+ ```ruby
479
+ if verify_recaptcha(action: 'login')
480
+ redirect_to @user
481
+ else
482
+ score = recaptcha_reply['score']
483
+ Rails.logger.warn("User #{@user.id} was denied login because of a recaptcha score of #{score}")
484
+ render 'new'
485
+ end
486
+ ```
487
+
488
+ `recaptcha_reply` will return `nil` if the the reply was not yet fetched.
489
+
490
+ ## I18n support
491
+
492
+ reCAPTCHA supports the I18n gem (it comes with English translations)
493
+ To override or add new languages, add to `config/locales/*.yml`
494
+
495
+ ```yaml
496
+ # config/locales/en.yml
111
497
  en:
112
498
  recaptcha:
113
499
  errors:
114
- incorrect-captcha-sol: 'Fail'
500
+ verification_failed: 'reCAPTCHA was incorrect, please try again.'
501
+ recaptcha_unreachable: 'reCAPTCHA verification server error, please try again.'
115
502
  ```
116
503
 
117
504
  ## Testing
118
505
 
119
506
  By default, reCAPTCHA is skipped in "test" and "cucumber" env. To enable it during test:
120
507
 
121
- ```Ruby
508
+ ```ruby
122
509
  Recaptcha.configuration.skip_verify_env.delete("test")
123
510
  ```
124
511
 
@@ -126,24 +513,29 @@ Recaptcha.configuration.skip_verify_env.delete("test")
126
513
 
127
514
  ### Recaptcha.configure
128
515
 
129
- ```Ruby
516
+ ```ruby
130
517
  # config/initializers/recaptcha.rb
131
518
  Recaptcha.configure do |config|
132
- config.public_key = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
133
- config.private_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
519
+ config.site_key = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
520
+ config.secret_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
521
+
134
522
  # Uncomment the following line if you are using a proxy server:
135
523
  # config.proxy = 'http://myproxy.com.au:8080'
136
- # config.disable_ssl_verification # if you do not want to verify ssl connection
524
+
525
+ # Uncomment the following lines if you are using the Enterprise API:
526
+ # config.enterprise = true
527
+ # config.enterprise_api_key = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA'
528
+ # config.enterprise_project_id = 'my-project'
137
529
  end
138
530
  ```
139
531
 
140
532
  ### Recaptcha.with_configuration
141
533
 
142
- For temporary overwrites (not thread safe).
534
+ For temporary overwrites (not thread-safe).
143
535
 
144
- ```Ruby
145
- Recaptcha.with_configuration(public_key: '12345') do
146
- # Do stuff with the overwritten public_key.
536
+ ```ruby
537
+ Recaptcha.with_configuration(site_key: '12345') do
538
+ # Do stuff with the overwritten site_key.
147
539
  end
148
540
  ```
149
541
 
@@ -151,12 +543,12 @@ end
151
543
 
152
544
  Pass in keys as options at runtime, for code base with multiple reCAPTCHA setups:
153
545
 
154
- ```Ruby
155
- recaptcha_tags public_key: '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
546
+ ```ruby
547
+ recaptcha_tags site_key: '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
156
548
 
157
- and
549
+ # and
158
550
 
159
- verify_recaptcha private_key: '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
551
+ verify_recaptcha secret_key: '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
160
552
  ```
161
553
 
162
554
  ## Misc