ViewComponent and Stimulus controller for integration with Cloudflare Turnstile
Firstly you need to set CLOUDFLARE_TURNSTILE_SITEKEY and CLOUDFLARE_TURNSTILE_SECRET in your environment. Test keys are available if you've not got actual keys/secrets to hand.
To use the component in your page, you can render the RpiTurnstile::TurnstileComponent in your view or component, inside the form that needs the check.
<%= form_with do |form| %>
<%= render RpiTurnstile::TurnstileComponent.new %>
<%= form.submit "Submit" %>
<% end %>Then in the controller that handles the POST from the form, include the RpiTurnstile::Verifiable module, which adds in the rpi_turnstile_verified? method, which you can call to check the validity of the form.
include RpiTurnstile::Verifiable
def submit
# Do some real work here...
notice = rpi_turnstile_verified? ? "✅" : "❌"
redirect_to '/', notice:
endCheck out the Home controller in the dummy app and its associated views.
There are myriad options that the widget can take. You can pass any of these options in to the component as arguments. e.g.
- language (default to
I18n.localeoren) - theme
- size
The options should be exactly as shown in the docs, i.e. with dashes rather than the more usual underscores encountered in Ruby. You can also add HTML attributes through the attrs parameter, e.g. class, id, etc.
To make use of these options, add them to the new call when rendering.
render RpiTurnstile::TurnstileComponent.new(attrs: { class: 'my-extra-css', id: 'woo'}, size: 'compact')In order for the component to render, you need to set the site key. Also when testing you might want to check what happens when verification fails.
Firstly, to stub the site key, you need to stub the RpiTurnstile::Api::SITEKEY constant with a value.
stub_const('RpiTurnstile::Api::SITEKEY', 'abc')That should allow the component to render.
Secondly, to stub and check what happens when the API verifies (or not), you can stub the RpiTurnstile::Api#siteverify class method:
allow(RpiTurnstile::Api).to receive(:siteverify).and_return(true)
Return false here if you want verification to fail.
Add this line to your application's Gemfile:
gem "rpi_turnstile"And then execute:
$ bundleOr install it yourself as:
$ gem install rpi_turnstileTo see the component in the demo app, run
bundle exec rails s
and head to port 3000.
The gem is available as open source under the terms of the MIT License.