Coder Social home page Coder Social logo

craft-recaptcha's Introduction

Craft reCAPTCHA plugin for Craft CMS 4.x

Integrate Google’s reCAPTCHA into your forms. Includes support for the CraftCMS Contact Form plugin.

Requirements

This plugin requires Craft CMS 4 or later.

This plugin supports reCAPTCHA v2 only.

Installation

To install the plugin, follow these instructions.

  1. Open your terminal and go to your Craft project:

     cd /path/to/project
    
  2. Then tell Composer to load the plugin:

     composer require matt-west/craft-recaptcha
    
  3. In the Control Panel, go to Settings → Plugins and click the “Install” button for Craft reCAPTCHA.

Configuring Craft reCAPTCHA

  1. Sign up for reCAPTCHA API key.
  2. Open the Craft admin and go to Settings → Plugins → Craft reCAPTCHA → Settings.
  3. Add your site key and secret key, then save.
  4. Add the reCAPTCHA template tag to your forms. (see next section)

If you’re using the CraftCMS Contact Form plugin, everything is already set up for you.

Verify the reCAPTCHA

To verify the reCAPTCHA is valid, pass the reCAPTCHA response from the g-recaptcha-response param to the verify() method on CraftRecaptcha::$plugin->craftRecaptchaService.

// Get the reCAPTCHA response code to validate.
$captcha = Craft::$app->getRequest()->getParam('g-recaptcha-response');

// Pass the response code to the verification service.
$validates = CraftRecaptcha::$plugin->craftRecaptchaService->verify($captcha);

if ($validates) {
  // All good! the reCAPTCHA is valid.
} else {
  // The reCAPTCHA is invalid.
}

Or alternatively, use the in-built verification controller action to verify the request before forwarding it on to the intended action.

For example, the following fields would verify the reCAPTCHA and then pass the request to the login controller action:

<input type="hidden" name="action" value="recaptcha/recaptcha/verify-submission">
<input type="hidden" name="verified-action" value="users/login">
{{ craft.recaptcha.render() }}

Set the action field to be recaptcha/recaptcha/verify-submission and the verified-action field to be the intended controller action you want to trigger. This will forward all other fields and parameters to the intended controller action.

Automated testing and reCAPTCHA

If you need to run automated tests against your forms use the following keys. Verification requests using these credentials will always pass.

Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

Documentation

Using Craft reCAPTCHA

Add the following tag to your form where you’d like the reCAPTCHA to be displayed.

{{ craft.recaptcha.render() }}

Render parameters per the documentation are injectable to the render() function, e.g.

{{ craft.recaptcha.render({
  theme: 'dark',
  size: 'compact'
}) }}

You can also create the reCAPTCHA element yourself using the sitekey template variable. This is especially useful for implementing invisible recaptcha.

<div class="g-recaptcha"
      data-sitekey="{{ craft.recaptcha.sitekey }}"
      data-callback="onSubmit"
      data-size="invisible">
</div>

Brought to you by Matt West

craft-recaptcha's People

Contributors

andreapasotti avatar billythekid avatar bossanova808 avatar domstubbs avatar honsa avatar martywallace avatar matt-west avatar mdxdave avatar parwinderd4d avatar totov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

craft-recaptcha's Issues

Render multiple recaptcha's not working

I try to load 3 recaptcha's on 1 page, but they are all provided with the same ID so some forms are failing to send because of this (i think)

I'm just adding
{{ craft.recaptcha.render() }}
to my forms, but i can't give them explicit ID like seen on this page: https://developers.google.com/recaptcha/docs/display (scroll to bottom 'Explicit rendering for multiple widgets')
The ID is set by the plugin:

'id' => 'gRecaptchaContainer',
can this be made optional?

It would be awesome to do something like this:
{{ craft.recaptcha.render('ID-OF-ELEMENT', { 'sitekey' : 'your_site_key', 'theme' : 'light' }) }}

Using Recaptcha on users/save-user / registration form breaks csrf protection

I've hit an issue with craft-recaptcha where a clients user registration form stopped working when craft-recaptcha was added to it. Specifically the form always failed crsf token verification.

  • Other forms on the same site with csrf protection work fine
  • This was only happening in their production environment (which incidentally - or not?) is also the only one using https
  • removing craft-recaptcha from the form caused it to start working again.

Are there any known issues with this plugin and CSRF protection and HTTPS requests?

More details:

This works (passes csrf protection):

    <form method="post" accept-charset="UTF-8" >
        {{ csrfInput() }}
        {{ actionInput('users/save-user') }}
        {{ redirectInput('account/verify') }}
        {% include 'account/_includes/profile-fields' %}
        <input class="btn" type="submit" value="Register">
    </form>

This fails (crsf token not verified)

    <form method="post" accept-charset="UTF-8">
        {{ csrfInput() }}
        {{ actionInput('recaptcha/recaptcha/verify-submission') }}
        {{ hiddenInput('verified-action', 'users/save-user' )}}
        {{ redirectInput('account/verify') }}
        {% include 'account/_includes/profile-fields' %}
        {{ craft.recaptcha.render() }}
        <input class="btn" type="submit" value="Register">
    </form>

I am running:

Craft 3.6.12.1
craft-recaptcha 1.5.1

Add forced test key + secret for local testing

Google's docs say that if you add this test key and secret, you can test locally and get a success every time:

  • Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
  • Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

It would be cool if the plugin automatically did this if it was being used in the local environment.

recaptcha script tag not rendered when ajax request

Apparently in Craft 3, the registered js files don't get dumped if the response is an HTML fragment (ie it doesn't have html/body tags). In craft 2 it would still dump those scripts at the bottom of the template.

To do this with this plugin, you can do something like this in your ajax template:

{{ view.getBodyHtml()|raw }}

Internal server error

Hi, I've added the plugin manually to an existing project. Installed with composer locally, then uploaded the plugin with ftp, same for the craftcms/plugins.php file. I installed and configured the plugin, and try to use it with the official craft form plugin.

With the plugin active and Enable to automatically validate reCAPTCHAs when using the official Craft CMS contact form plugin.
enabled, it shows an internal server error page after submitting forms.

This is a related part of the craft log of the failing post requests:

$_POST = [
    'CRAFT_CSRF_TOKEN' => '•••••••'
    'action' => 'contact-form/send'
    'redirect' => 'b3c09816c20395ae7fce033801aaaf66a3917d9a37231ebb615bc7c5e8426d64url
    'subject' => 'subject'
    'fromName' => 'jnaklaas'
    'message' => [
        'body' => 'TEST'
    ]
    'fromEmail' => '[email protected]'
]

$_SESSION = [
    'bd62416aa8538ede709019a5e113eea5__flash' => [
        'error' => 1
    ]
    '1031b8c41dfff97a311a7ac99863bdc5__id' => '1'
    '1031b8c41dfff97a311a7ac99863bdc5__expire' => 1639052986
    'error' => 'There was a problem with your submission, please check the form and try again!'
]

When disabling the auto validation, the form works properly.

The web inspector shows no requests to google's recaptcha.js file - I'm not sure if this is expected behaviour. Adding code below does load the recaptcha.js. But it still doesn't show a badge - and still shows the internal server error page on submit.

{{ craft.recaptcha.render({
  callback: 'onSubmit',
  size: 'invisible',
  badge: 'bottomright'
}) }}

craft cms version: 3.0.32
contact-form version: 2.2.2
craft-recaptcha version: 1.2.0

Issue with latest Craft / Commerce - needs Guzzle 7.

It seems all the payment gateways for Commerce have moved to requiring Guzzle 7, which means those now conflict with this plugin:

  Problem 1
    - Root composer.json requires craftcms/commerce-eway ^3.0.0 -> satisfiable by craftcms/commerce-eway[3.0.0].
    - Conclusion: don't install craftcms/cms[3.6.11.2] | install guzzlehttp/guzzle[7.2.0] (conflict analysis result)
    - Conclusion: don't install guzzlehttp/guzzle 7.2.0 (conflict analysis result)
    - Conclusion: don't install guzzlehttp/guzzle 7.3.0 (conflict analysis result)
    - Conclusion: don't install craftcms/cms 3.6.12 (conflict analysis result)
    - Root composer.json requires matt-west/craft-recaptcha ^1.0 -> satisfiable by matt-west/craft-recaptcha[1.0.0, ..., 1.5.1].
    - craftcms/commerce-eway 3.0.0 requires craftcms/cms ^3.6 -> satisfiable by craftcms/cms[3.6.0-beta.1, ..., 3.6.12].
    - craftcms/cms[3.6.0-beta.1, ..., 3.6.11.1] require guzzlehttp/guzzle ^6.5.5|^7.2.0 -> satisfiable by guzzlehttp/guzzle[6.5.5, 7.2.0, 7.3.0].
    - Conclusion: don't install guzzlehttp/guzzle 6.5.5 (conflict analysis result)

I don't immediately need to upgrade those, as they're just dependency changes and not functionality ones, it seems...but this is a sign of the future I think and I am hoping you'd be willing to update this one to be guzzle 7 friendly?

Validation within twig template

I have a custom form (so no Craft Contact Form) with the action to send to an external URL (Salesforce Web to Case). The reCaptcha widget displays fine with
{{ craft.recaptcha.render() }}

but implementation of the validation function:
`// Get the reCAPTCHA response code to validate.
$captcha = Craft::$app->getRequest()->getParam('g-recaptcha-response');

    // Pass the response code to the verification service.
    $validates = CraftRecaptcha::$plugin->craftRecaptchaService->verify($captcha);

    if ($validates) {
    // All good! the reCAPTCHA is valid.
    } else {
    // The reCAPTCHA is invalid.
    }`

is unclear, and the form sends regardless of user interaction with the widget.

No error handling when craft-recaptcha is active

When the craft-recaptcha plugin is active, no errors are display on the fields used in the contact form.

The captcha itself is rendered by:
{{ craft.recaptcha.render() }}

The errors for the fields used in the contact form are rended by:
{{ message is defined and message ? errorList(message.getErrors('message.body')) }}

Only when the "I'm not a robot" in the Recaptcha box is checked, errors are displayed.

Expectation

  • Show an error when the recaptcha box is not checked.
  • Show errors when fields used in the contact form are not valid, even when the recaptcha box is not checked.

How to change re-captcha language based on current site language ?

Hi, could you please let me know how we can change Recaptcha language based on the website's current language?

For example: if a user opens a website in the French language then it will show Captcha text in French and the same for other languages, Please have a look at the screen-shot :
image

As I have done some RnD and found that we have to pass language code into javascript file as mentioned below in code.
<script src='https://www.google.com/recaptcha/api.js?hl=fr'></script>
and if follow the same thing so in the plugin core file I have added the ?hl=fr and it works fine.

could you please guide me on how I can make it work without doing changes in the core file?

Looking Forward.
Parwinder

Is this plugin support google recaptcha v3?

Hi,

Is this plugin support google recaptcha v3?

Some people think that google recaptcha v2 is too difficult to use:

https://productforums.google.com/forum/#!topic/websearch/tFHDAsX4Ypk

I think v3 is better to use:

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

Thanks:)

Contact Form passes through without recaptcha checked

I have added {{craft.recaptcha.render()}} to the form tag inside my contact.html form. When clicking the submit button with EMPTY recaptcha, the form goes through successfully.

I wasn't sure where to put the Verify the reCAPTCHA script so I just put it inside <script> tag on top of html.

Here are my questions:

  1. how can i make sure that the form does not go through unless the recaptcha is checked?
  2. Is the Verify the reCAPTCHA necessary? or can I just get the desired functionality with {{craft.recaptcha.render()}} tag.

Thanks in advance for your help! :)

Loading for SPA-style AJAX sites

I'm using Barba.js to load pages via AJAX for page transitions, and when my contact page is navigated to in this way, loading the ReCaptcha via {{ craft.recaptcha.render() }} (expectedly) doesn't show up.

Often with plugins like this, there's some sort of script block injected into the template I can run eval on after my page transition, but it appears the render() method just outputs an empty div with id=gRecaptchaContainer in this case.

Is there a window method I can call after page transition to kick off the needed functionality? Or any other suggestions you might have?

Incompatible with Commerce 4

Hiya,

Thanks for this plugin, it's a really elegant, simple and flexible solution for recaptcha. In Craft 3 I was using it to protect a Commerce (Stripe) checkout form, as the client was receiving a lot of Card Testing fraud/spam submissions of the checkout form (Stripe actually asked the client to install a captcha). It works well.

However, I'm upgrading now to Craft 4/Commerce 4, and the Stripe checkout form fields will only appear if the form contains the standard Commerce hidden action input i.e. {{ actionInput('commerce/payments/pay') }}. So I can't hijack it with this plugin like I used to. Not sure about how to solve this, but would be great if anyone has any ideas to get this working.

Thanks

How to disable the recaptcha check on ajax forms

Got this running perfectly on the standard craft contact form and plug in.

I've a different form I'm submitting via post request (generated via axois). Its failing because, obviously, its looking for the recaptcha fields.

Is there a way to say to this plug in "don't try and validate for XXX form?"

Why return null? In Craft 4, controllers generally return a status code of 400 and a message if there is an error

https://github.com/matt-west/craft-recaptcha/blob/d95e16a559899dca16afd50ecb88452569ecf216/src/controllers/RecaptchaController.php#LL40C4-L40C16

I don't understand the behaviour or intention of returning null here (albeit this was the Craft 3 way I suppose).

If I e.g. use this to try and verify a user registration form, then if the recaptcha fails, I get a 404 not found response, which is...odd.

In an ajax scenario this is awkward (at best) to handle, and the flash message of Unable to verify your submission is not accessible via javascript (I believe?).

Controllers in Craft 4 should be using the new asSuccess and asFailure returns, with an optional message. See:
https://craftcms.com/docs/4.x/extend/updating-plugins.html#controller-responses

So really this should be something like:

$error = "Unable to verify your submission";
return $this->asFailure($error, [], ['message' => $error]);`

That will return the correct 400 status code, set a message in the routeParams and a message in the repsonseJSON so that in your error handler you can then e.g.

                    // Handle errors coming back from Craft
                    if (request.status === 400){
                         console.log(request.responseJSON);
                    }

Would you accept a PR for this change? It will obviously change the behaviour, but would be changing it to the proper Craft 4 way (as I understand it!)

Badge not showing for Invisible reCaptcha

I'm using invisible reCaptcha with the Craft CMS Contact Form plugin. As far as I can tell it's working ok, but I can't get the badge to show up. I tried the automatic integration as well as adding this to the form markup (right before the submit button):

<div class="g-recaptcha"
  data-sitekey="{{ craft.recaptcha.sitekey }}"
  data-callback="onSubmit"
  data-size="invisible"
  data-badge="bottomright">
</div>

Any idea what to try next? Thanks.

Site isn't verifying reCAPTCHA solutions

In the Google reCAPTCHA control panel in the last few days I've started getting a warning message:
"We detected that your site isn't verifying reCAPTCHA solutions. This is required for the proper use of reCAPTCHA on your site. Please see our developer site for more information."

In the Firefox developer tools Console I get multiple:
"Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified"
"Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified"
"Partitioned cookie or storage access was provided to “https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LfxOHohAAAAACE2XgP5V9K9PDJfFXfkDMOd_xoR&co=aHR0cHM6Ly93d3cuZGZvay5jby51azo0NDM.&hl=en-GB&v=g8G8cw32bNQPGUVoDvt680GA&size=normal&cb=mjvhmicq3dqd” because it is loaded in the third-party context and dynamic state partitioning is enabled."

But the graph showing requests passed and failed still reports numbers for recent days and the form is still showing the reCAPTCHA and sending on emails.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.