recaptcha 1.3.0 → 5.7.0

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