Skip to content

Commit

Permalink
Merge pull request #23 from rubekx/feature/hcaptcha-enable-disable
Browse files Browse the repository at this point in the history
Feature/hcaptcha enable disable
  • Loading branch information
Scyllaly authored Aug 31, 2024
2 parents 5b7d5ec + 31f4f53 commit f5d3d66
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 11 deletions.
33 changes: 30 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@ php artisan vendor:publish --provider="Scyllaly\HCaptcha\HCaptchaServiceProvider

### Configuration

Add `HCAPTCHA_SECRET` and `HCAPTCHA_SITEKEY` in **.env** file :
Add `HCAPTCHA_SECRET`, `HCAPTCHA_SITEKEY` and `HCAPTCHA_ENABLED` in **.env** file :

```
HCAPTCHA_SECRET=secret-key
HCAPTCHA_SITEKEY=site-key
HCAPTCHA_ENABLED=true
```

(You can obtain them from [Official Developer Guide](https://docs.hcaptcha.com/api#getapikey))
Expand Down Expand Up @@ -89,15 +90,41 @@ callback submit the form on a successful captcha verification.

#### Validation

Add `'h-captcha-response' => 'required|HCaptcha'` to rules array :
There are two ways to apply HCaptcha validation to your form:

#### 1. Basic Approach

This method always applies the HCaptcha validation rule.

```php
$validate = Validator::make(Input::all(), [
'h-captcha-response' => 'required|HCaptcha'
'h-captcha-response' => 'required|HCaptcha'
]);

```

In this approach, the `h-captcha-response` field is required and validated using the `HCaptcha` rule without any conditions.

#### 2. Conditional Approach

This method applies the HCaptcha validation rule only if the `HCAPTCHA_ENABLED` environment variable is set to `true`.

```php
$isHcaptchaEnabled = env('HCAPTCHA_ENABLED');
$rules = [
// Other validation rules...
];

if ($isHcaptchaEnabled) {
$rules['h-captcha-response'] = 'required|HCaptcha';
}

$request->validate($rules);

```

In this approach, the `h-captcha-response` field will be required and validated using the `HCaptcha` rule only when `HCAPTCHA_ENABLED` is set to `true`. This adds flexibility to your validation logic, allowing you to enable or disable HCaptcha validation as needed.

##### Custom Validation Message

Add the following values to the `custom` array in the `validation` language file :
Expand Down
40 changes: 34 additions & 6 deletions src/HCaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,26 +35,34 @@ class HCaptcha
* @var array
*/
protected $verifiedResponses = [];

/**
* @var null
* lastScore
*/
protected $lastScore = null;



/**
* Whether to use hCaptcha or not.
*
* @var bool
*/
protected $enabled;

/**
* HCaptcha.
*
* @param string $secret
* @param string $sitekey
* @param array $options
* @param bool $enabled
*/
public function __construct($secret, $sitekey, $options = [])
public function __construct($secret, $sitekey, $options = [], $enabled = true)
{
$this->secret = $secret;
$this->sitekey = $sitekey;
$this->http = new Client($options);
$this->enabled = $enabled;
}

/**
Expand All @@ -66,6 +74,10 @@ public function __construct($secret, $sitekey, $options = [])
*/
public function display($attributes = [])
{
if (!$this->enabled) {
return '';
}

$attributes = $this->prepareAttributes($attributes);
return '<div' . $this->buildAttributes($attributes) . '></div>';
}
Expand All @@ -89,6 +101,10 @@ public function displayWidget($attributes = [])
*/
public function displaySubmit($formIdentifier, $text = 'submit', $attributes = [])
{
if (!$this->enabled) {
return sprintf('<button%s><span>%s</span></button>', $this->buildAttributes($attributes), $text);
}

$javascript = '';
if (!isset($attributes['data-callback'])) {
$functionName = 'onSubmit' . str_replace(['-', '=', '\'', '"', '<', '>', '`'], '', $formIdentifier);
Expand Down Expand Up @@ -118,6 +134,10 @@ public function displaySubmit($formIdentifier, $text = 'submit', $attributes = [
*/
public function renderJs($lang = null, $callback = false, $onLoadClass = 'onloadCallBack')
{
if (!$this->enabled) {
return '';
}

return '<script src="' . $this->getJsLink($lang, $callback, $onLoadClass) . '" async defer></script>' . "\n";
}

Expand All @@ -131,11 +151,15 @@ public function renderJs($lang = null, $callback = false, $onLoadClass = 'onload
*/
public function verifyResponse($response, $clientIp = null)
{
if (!$this->enabled) {
return true; // Always true if hCaptcha is disabled
}

if (empty($response)) {
return false;
}

// Return true if response already verfied before.
// Return true if response already verified before.
if (in_array($response, $this->verifiedResponses)) {
return true;
}
Expand Down Expand Up @@ -194,6 +218,10 @@ public function verifyRequest(Request $request)
*/
public function getJsLink($lang = null, $callback = false, $onLoadClass = 'onloadCallBack')
{
if (!$this->enabled) {
return '';
}

$client_api = static::CLIENT_API;
$params = [];

Expand All @@ -202,7 +230,7 @@ public function getJsLink($lang = null, $callback = false, $onLoadClass = 'onloa

return $client_api . '?' . http_build_query($params);
}

/**
* Get the score from the last successful hCaptcha verification.
*
Expand Down
6 changes: 4 additions & 2 deletions src/HCaptchaServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,15 @@ public function register()
return new HCaptcha(
$hCaptcha['secret'],
$hCaptcha['sitekey'],
$hCaptcha['options']
$hCaptcha['options'],
$hCaptcha['enabled'],
);
} else {
return new HCaptcha(
$app['config']['HCaptcha.secret'],
$app['config']['HCaptcha.sitekey'],
$app['config']['HCaptcha.options']
$app['config']['HCaptcha.options'],
$app['config']['HCaptcha.enabled'],
);
}
});
Expand Down
1 change: 1 addition & 0 deletions src/config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
return [
'secret' => env('HCAPTCHA_SECRET'),
'sitekey' => env('HCAPTCHA_SITEKEY'),
'enabled' => env('HCAPTCHA_ENABLED', true), //Enable or disable hCaptcha for development environments
'server-get-config' => false,
'options' => [
'timeout' => 30,
Expand Down

0 comments on commit f5d3d66

Please sign in to comment.