Skip to content

Commit

Permalink
refactor to guzzle client and environment variables (#13)
Browse files Browse the repository at this point in the history
* peer review changes

* peer review changes

* peer review changes

* Cleanup docs

* test field validate

* correct extension syntax

---------

Co-authored-by: Bernie Hamlin <[email protected]>
  • Loading branch information
DevKCode and blueo authored Jun 30, 2023
1 parent 781d3ad commit 123ecae
Show file tree
Hide file tree
Showing 19 changed files with 318 additions and 303 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.vscode
composer.lock
public
vendor
101 changes: 31 additions & 70 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,16 @@ Adds a "spam protection" field to SilverStripe userforms using Cloudflare's
## Requirements
* SilverStripe 5.x
* [SilverStripe Spam Protection
3.x](https://github.com/silverstripe/silverstripe-spamprotection/)
* PHP CURL
4.x](https://github.com/silverstripe/silverstripe-spamprotection/)

## Installation
```
composer require silverstripe-terraformers/turnstile-captcha
```

After installing the module via composer or manual install you must set the spam
protector to NocaptchaProtector, this needs to be set in your site's config file
normally this is mysite/\_config/config.yml.
protector to TurnstileCaptchaProtector, this needs to be set in your site's config file
normally this is mysite/_config/config.yml.
```yml
SilverStripe\SpamProtection\Extension\FormSpamProtectionExtension:
default_spam_protector: Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaProtector
Expand All @@ -30,30 +29,38 @@ $form->enableSpamProtection();
```

## Configuration
There are multiple configuration options for the field, you must set the
site_key and the secret_key which you can get from the [reCAPTCHA
page](https://www.google.com/recaptcha). These configuration options must be
added to your site's yaml config typically this is mysite/\_config/config.yml.
Set the `site_key` and the `secret_key` via [environment variables](https://docs.silverstripe.org/en/5/getting_started/environment_management/).

```yml
SS_TURNSTILE_SITE_KEY=""
SS_TURNSTILE_SECRET_KEY=""
```

You can get these from your cloudflare account [refer to the turnstile documentation](https://developers.cloudflare.com/turnstile/).

There are some optional configuration settings that can be
added to your site's yaml config (typically this is mysite/_config/config.yml).
```yml
Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaField:
site_key: "YOUR_SITE_KEY" #Your site key (required)
secret_key: "YOUR_SECRET_KEY" #Your secret key (required)
verify_ssl: true #Allows you to disable php-curl's SSL peer verification by setting this to false (optional, defaults to true)
default_theme: "light" #Default theme color (optional, light or dark, defaults to light)
default_handle_submit: true #Default setting for whether nocaptcha should handle form submission. See "Handling form submission" below.
proxy_server: "" #Your proxy server address (optional)
proxy_port: "" #Your proxy server address port (optional)
proxy_auth: "" #Your proxy server authentication information (optional)
default_theme: "light" #Default theme color (optional, light or dark, defaults to auto)
default_render_type: 'explicit' #Default setting for how to render the widget. See the "Render Type" section below.
```
TurnstileCaptchaField uses Guzzle to communicate with cloudflare. If you would like to change http connection settings (Eg proxy settings) you can configure your own HttpClient class via injector
```yml
SilverStripe\Core\Injector\Injector:
Terraformers\TurnstileCaptcha\Http\HttpClient:
class: App\HttpClient
```
## Adding field labels
If you want to add a field label or help text to the Captcha field you can do so
If you want to add a field label or help text to the TurnstileCaptchaField field you can do so
like this:
```php
$form->enableSpamProtection()
->fields()->fieldByName('Captcha')
->fields()->fieldByName('TurnstileCaptchaField')
->setTitle("Spam protection")
->setDescription("Please tick the box to prove you're a human and help us stop spam.");
```
Expand All @@ -68,68 +75,22 @@ in order to use Terraformers\TurnstileCaptcha on comment forms.
CommentingController::add_extension('CommentSpamProtection');
```

## Retrieving the Verify Response

If you wish to manually retrieve the Site Verify response in you form action use
the `getVerifyResponse()` method

```php
function doSubmit($data, $form) {
$captchaResponse = $form->Fields()->fieldByName('Captcha')->getVerifyResponse();

// $captchaResponse = array (size=5) [
// 'success' => boolean true
// 'challenge_ts' => string '2020-09-08T20:48:34Z' (length=20)
// 'hostname' => string 'localhost' (length=9)
// 'score' => float 0.9
// 'action' => string 'submit' (length=6)
// ];
}
```

## Handling form submission
By default, the javascript included with this module will add a submit event handler to your form.

If you need to handle form submissions in a special way (for example to support front-end validation),
you can choose to handle form submit events yourself.
## Render type
By default, the turnstyle widget will be rendered automatically. To change this you can set the render type.

This can be configured site-wide using the Config API
```yml
Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaField:
default_handle_submit: false
default_render_type: 'explicit'
```
Or on a per form basis:
```php
$captchaField = $form->Fields()->fieldByName('Captcha');
$captchaField->setHandleSubmitEvents(false);
$captchaField = $form->Fields()->fieldByName('TurnstileCaptchaField');
$captchaField->setRenderType('explicit');
```

With this configuration no event handlers will be added by this module to your form. Instead, a
function will be provided called `nocaptcha_handleCaptcha` which you can call from your code
when you're ready to submit your form. It has the following signature:
```js
function nocaptcha_handleCaptcha(form, callback)
```
`form` must be the form element, and `callback` should be a function that finally submits the form,
though it is optional.

In the simplest case, you can use it like this:
```js
document.addEventListener("DOMContentLoaded", function(event) {
// where formID is the element ID for your form
const form = document.getElementById(formID);
const submitListener = function(event) {
event.preventDefault();
let valid = true;
/* Your validation logic here */
if (valid) {
nocaptcha_handleCaptcha(form, form.submit.bind(form));
}
};
form.addEventListener('submit', submitListener);
});
```
With this configuration you will need to add your own javascript to render the widget. Refer to the [cloudflare documentation](https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/#explicitly-render-the-turnstile-widget) for details.

## Reporting an issue

Expand Down
9 changes: 7 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@
],
"require": {
"php": "^8.1",
"ext-intl": "*",
"silverstripe/framework": "^5.0",
"silverstripe/spamprotection": "^3 | ^4"
"silverstripe/spamprotection": "^4"
},
"require-dev": {
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"Terraformers\\TurnstileCaptcha\\": "src/"
"Terraformers\\TurnstileCaptcha\\": "src/",
"Terraformers\\TurnstileCaptcha\\Test\\": "tests/"
}
},
"extra": {
Expand Down
2 changes: 1 addition & 1 deletion lang/de.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
de:
Terraformers\TurnstileCaptcha\Forms\CaptchaField:
Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaField:
NOSCRIPT: "Sie müssen JavaScript aktivieren um dieses Formular zu übermitteln"
VALIDATE_ERROR: "Spam-Schutz konnte nicht geprüft werden"
2 changes: 1 addition & 1 deletion lang/en.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
en:
Terraformers\TurnstileCaptcha\Forms\CaptchaField:
Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaField:
NOSCRIPT: "You must enable JavaScript to submit this form"
VALIDATE_ERROR: "Captcha could not be validated"
2 changes: 1 addition & 1 deletion lang/fr.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fr:
Terraformers\TurnstileCaptcha\Forms\CaptchaField:
Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaField:
NOSCRIPT: "Vous devez activer JavaScript pour soumettre ce formulaire"
VALIDATE_ERROR: "Captcha n'a pas pu être validé"
2 changes: 1 addition & 1 deletion lang/ru.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ru:
Terraformers\TurnstileCaptcha\Forms\CaptchaField:
Terraformers\TurnstileCaptcha\Forms\TurnstileCaptchaField:
NOSCRIPT: "Укажите ответ на капчу, если вы её не видите вам необходимо включить JavaScript."
VALIDATE_ERROR: "Ошибка проверки капчи - попробуйте ещё раз."
4 changes: 2 additions & 2 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/silverstripe/framework/tests/bootstrap.php" colors="true">
<phpunit bootstrap="vendor/silverstripe/framework/tests/bootstrap.php" colors="true" defaultTestSuite="Default">
<testsuites>
<testsuite name="Default">
<directory>tests/php</directory>
<directory suffix=".php">tests</directory>
</testsuite>
</testsuites>
</phpunit>
Loading

0 comments on commit 123ecae

Please sign in to comment.