Skip to content
This repository has been archived by the owner on Feb 17, 2022. It is now read-only.

Commit

Permalink
Changed ReCaptchaResponseHolder to literally just ReCaptcha.
Browse files Browse the repository at this point in the history
Changed script function
  • Loading branch information
DarkGhostHunter committed Apr 3, 2019
1 parent a3f4d8d commit f4863c0
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 89 deletions.
64 changes: 35 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

Easily integrate Google reCAPTCHA v3 into your Laravel application.

> This is totally compatible with reCAPTCHA v2, so you can use both.
> This is totally compatible with reCAPTCHA v2, so you can use both. Check [this GitHub comment](https://github.com/google/recaptcha/issues/279#issuecomment-445529732) about the caveats.
## Installation

Expand Down Expand Up @@ -105,7 +105,11 @@ Route::post('form')->uses('CustomController@form')->middleware('recaptcha');
### Accessing the reCAPTCHA response

You can access the reCAPTCHA response in three ways: using the `ReCaptcha` facade, the `recaptcha()` helper, and just resolving it from the Service Container with `app('recaptha')`.
You can access the reCAPTCHA response in four ways ways:
* using [dependency injection](https://laravel.com/docs/container#automatic-injection),
* using the `ReCaptcha` facade anywhere in your code,
* the `recaptcha()` helper,
* and resolving it from the Service Container with `app('recaptha')`.

These methods will return the reCAPTCHA Response from the servers, with useful helpers so you don't have to dig in the raw response:

Expand All @@ -115,7 +119,7 @@ These methods will return the reCAPTCHA Response from the servers, with useful h
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DarkGhostHunter\Captchavel\Facades\ReCaptcha;
use DarkGhostHunter\Captchavel\ReCaptcha;

class CustomController extends Controller
{
Expand All @@ -133,15 +137,16 @@ class CustomController extends Controller
* Receive the HTTP POST Request
*
* @param \Illuminate\Http\Request $request
* @param \DarkGhostHunter\Captchavel\ReCaptcha $reCaptcha
* @return \Illuminate\Http\Response
*/
public function form(Request $request)
public function form(Request $request, ReCaptcha $reCaptcha)
{
$request->validate([
'username' => 'required|string|exists:users,username'
]);

if (ReCaptcha::isRobot()) {
if ($reCaptcha->isRobot()) {
return response()->view('web.user.you-are-a-robot');
}

Expand All @@ -154,7 +159,7 @@ class CustomController extends Controller

The class has handy methods you can use to check the status of the reCAPTCHA information:

* `isResolved()`: Returns if the reCAPTCHA check was made in the current Request.
* `isResolved()`: Returns if the reCAPTCHA check was made in the current Request
* `isHuman()`: Detects if the Request has been made by a Human (equal or above threshold).
* `isRobot()`: Detects if the Request has been made by a Robot (below threshold).
* `since()`: Returns the time the reCAPTCHA challenge was resolved as a Carbon timestamp.
Expand All @@ -163,9 +168,9 @@ The class has handy methods you can use to check the status of the reCAPTCHA inf

When developing, this package registers a transparent middleware that allows you to work on your application without contacting reCAPTCHA servers ever. Instead, it will always generate a successful "dummy" response with a `1.0` score.

You can override the score to an absolute `0.0` with:
You can override the score to an absolute `0.0` in two ways:

* appending the `is_robot` to the Request query,
* appending the `is_robot` key to the Request query,

```http request
POST http://myapp.com/login?is_robot
Expand All @@ -186,7 +191,7 @@ POST http://myapp.com/login?is_robot

If you want to connect to the reCAPTCHA servers on `local` environment, you can set the `CAPTCHAVEL_LOCAL=true` in your `.env` file.

> The transparent middleware also registers itself on testing environment, so you can test your application using requests made by a robot and made by a human, and an empty `_recaptcha` input.
> The transparent middleware also registers itself on testing environment, so you can test your application using requests made by a robot and made by a human just adding an empty `_recaptcha` input.
## Configuration

Expand Down Expand Up @@ -284,34 +289,31 @@ Aside from that, you can also override the score using a parameter within the `r

use Illuminate\Support\Facades\Route;

Route::post('form')
->uses('CustomController@form')
Route::post('{product]/review')
->uses('ReviewController@create')
->middleware('recaptcha:0.8');
```

> Issuing `null` as first parameter will make the middleware to use the default threshold.
### Request Method

The Google reCAPTCHA library underneath allows to make the request to the reCAPTCHA servers using a custom "Request Method".

The `request_method` accepts the Class you want to instance. You should register it using the Service Container [Contextual Binding](https://laravel.com/docs/container#contextual-binding).
The Google reCAPTCHA library underneath allows to make the request to the reCAPTCHA servers using a custom "Request Method". The `request_method` key accepts the Class you want to instance.

The default `null` value is enough for any normal application, but you're free to, for example, create your own logic or use the classes included in the [ReCaptcha package](https://github.com/google/recaptcha/tree/master/src/ReCaptcha/RequestMethod) (that this package requires). You can mimic this next example, were we will use Guzzle.


```php
<?php

return [

// ...

'request_method' => 'App\Http\ReCaptcha\GuzzleRequestMethod',
];
```


#### Example implementation

First, we will create our `GuzzleRequestMethod` with the `submit()` method as required. This method will return the reCAPTCHA response from the external server using Guzzle.
First, we will create our `GuzzleRequestMethod` with the `submit()` method as required. This method will return the reCAPTCHA response from the external server using the Guzzle Client.

`app\Http\ReCaptcha\GuzzleRequestMethod.php`
```php
Expand All @@ -328,19 +330,19 @@ class GuzzleRequestMethod implements RequestMethod
/**
* Submit the request with the specified parameters.
*
* @param RequestParameters $params Request parameters
* @return string Body of the reCAPTCHA response
* @param RequestParameters $params Request parameters
* @return string Body of the reCAPTCHA response
*/
public function submit(RequestParameters $params)
{
return (new \GuzzleHttp\Client)
->post($params->toQueryString())
->getBody();
return (new \GuzzleHttp\Client)->post($params->toQueryString())
->getBody()
->getContents();
}
}
```

Then, we will add the class to the `request_method` key in our configuration
Then, we will add the class to the `request_method` key in our configuration:

`config/captchavel.php`
```php
Expand All @@ -354,17 +356,17 @@ return [
];
```

And finally, we will tell the Service Container to give our `GuzzleRequestMethod` to the underneath `ReCaptcha` class when Captchavel tries to instance it.
Finally, we will tell the Service Container to give our `GuzzleRequestMethod` to the underneath `ReCaptcha` class when Captchavel tries to instance it, using the Service Container [Contextual Binding](https://laravel.com/docs/container#contextual-binding).

`app\Providers\AppServiceProvider.php`
```php
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Http\ReCaptcha\GuzzleRequestMethod;
use ReCaptcha\ReCaptcha;
use ReCaptcha\RequestMethod;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
Expand All @@ -377,6 +379,8 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
// ...

// Tell the Service Container to pass our custom Request Method to the ReCaptcha client
$this->app->when(ReCaptcha::class)
->needs(RequestMethod::class)
Expand All @@ -387,13 +391,15 @@ class AppServiceProvider extends ServiceProvider
}
```

We're leaving the Contextual Binding to you, since your *requester* may need some logic that a simple `app()->make(MyRequester::class)` may not be sufficient.

### Editing the Script view

You can edit the script Blade view under by just creating a Blade template in `resources/vendor/captchavel/script.blade.php`.

There you can edit how the script is downloaded from Google reCAPTCHA, and how it checks for forms to link with the check in the backend.
This blade views requires the Google reCAPTCHA v3 script, and detects the forms that need a reCAPTCHA check to be injected inside the request to the application. The view receives the `$key` variable witch is just the reCAPTCHA v3 Site Key.

The view receives the `$key` variable witch is just the reCAPTCHA Site Key.
There you can edit how the script is downloaded from Google, and how it checks for forms to link with the backend.

## License

Expand Down
5 changes: 2 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
],
"require": {
"php": "^7.1.3",
"ext-json" : "*",
"google/recaptcha": "^1.2",
"illuminate/config": "5.8.*",
"illuminate/container": "5.8.*",
Expand All @@ -31,9 +32,7 @@
},
"require-dev": {
"orchestra/testbench": "3.8.*",
"orchestra/testbench-dusk": "3.8.*",
"phpunit/phpunit": "^7.0",
"ext-json": "*"
"phpunit/phpunit": "^7.0"
},
"autoload": {
"files": [
Expand Down
2 changes: 1 addition & 1 deletion resources/views/script.blade.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script src="https://www.google.com/recaptcha/api.js?render={{ $key }}&onload=captchavelCallback" defer></script>
<script>
// Start Captchavel Script
window.captchavelCallback = () => {
window.captchavelCallback = function () {
let site_key = "{{ $key }}";
if (site_key === '') {
Expand Down
11 changes: 6 additions & 5 deletions src/CaptchavelServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
use DarkGhostHunter\Captchavel\Http\Middleware\InjectRecaptchaScript;
use DarkGhostHunter\Captchavel\Http\Middleware\TransparentRecaptcha;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use ReCaptcha\ReCaptcha;
use ReCaptcha\ReCaptcha as ReCaptchaFactory;

class CaptchavelServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -51,13 +52,13 @@ public function register()
$this->mergeConfigFrom(__DIR__.'/../config/captchavel.php', 'captchavel');

// When the application tries to resolve the ReCaptcha instance, we will pass the Site Key.
$this->app->when(ReCaptcha::class)
$this->app->when(ReCaptchaFactory::class)
->needs('$secret')
->give(function ($app) {
return $app->make('config')->get('captchavel.secret');
});

$this->app->singleton('recaptcha', RecaptchaResponseHolder::class);
$this->app->singleton('recaptcha', ReCaptcha::class);
}

/**
Expand Down Expand Up @@ -99,7 +100,7 @@ protected function shouldEnableMiddleware()
* @param \Illuminate\Routing\Router $router
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
protected function registerMiddleware(\Illuminate\Routing\Router $router)
protected function registerMiddleware(Router $router)
{
$router->aliasMiddleware('recaptcha', CheckRecaptcha::class);
$router->aliasMiddleware('recaptcha-inject', InjectRecaptchaScript::class);
Expand All @@ -114,7 +115,7 @@ protected function registerMiddleware(\Illuminate\Routing\Router $router)
*
* @param \Illuminate\Routing\Router $router
*/
protected function registerTransparentMiddleware(\Illuminate\Routing\Router $router)
protected function registerTransparentMiddleware(Router $router)
{
$router->aliasMiddleware('recaptcha', TransparentRecaptcha::class);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Facades/ReCaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* @method \ReCaptcha\Response response()
* @method \Illuminate\Support\Carbon getSince()
*
* @see \DarkGhostHunter\Captchavel\RecaptchaResponseHolder
* @see \DarkGhostHunter\Captchavel\ReCaptcha
*/
class ReCaptcha extends Facade
{
Expand Down
32 changes: 16 additions & 16 deletions src/Http/Middleware/CheckRecaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
use DarkGhostHunter\Captchavel\Exceptions\FailedRecaptchaException;
use DarkGhostHunter\Captchavel\Exceptions\InvalidCaptchavelMiddlewareMethod;
use DarkGhostHunter\Captchavel\Exceptions\InvalidRecaptchaException;
use DarkGhostHunter\Captchavel\RecaptchaResponseHolder as RecaptchaResponse;
use DarkGhostHunter\Captchavel\ReCaptcha;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Contracts\Validation\Factory as Validator;
use Illuminate\Http\Request;
use ReCaptcha\ReCaptcha as ResponseFactory;
use ReCaptcha\ReCaptcha as ReCaptchaFactory;

class CheckRecaptcha
{
Expand All @@ -33,32 +33,32 @@ class CheckRecaptcha
*
* @var \ReCaptcha\ReCaptcha
*/
protected $recaptchaFactory;
protected $reCaptchaFactory;

/**
* The reCAPTCHA response holder
*
* @var \DarkGhostHunter\Captchavel\RecaptchaResponseHolder
* @var \DarkGhostHunter\Captchavel\ReCaptcha
*/
protected $response;
protected $reCaptcha;

/**
* CheckRecaptcha constructor.
*
* @param \Illuminate\Contracts\Validation\Factory $validator
* @param \Illuminate\Contracts\Config\Repository $config
* @param \ReCaptcha\ReCaptcha $recaptchaFactory
* @param \DarkGhostHunter\Captchavel\RecaptchaResponseHolder $response
* @param \ReCaptcha\ReCaptcha $reCaptchaFactory
* @param \DarkGhostHunter\Captchavel\ReCaptcha $reCaptcha
*/
public function __construct(Validator $validator,
ResponseFactory $recaptchaFactory,
RecaptchaResponse $response,
Config $config)
Config $config,
ReCaptchaFactory $reCaptchaFactory,
ReCaptcha $reCaptcha)
{
$this->validator = $validator;
$this->recaptchaFactory = $recaptchaFactory;
$this->response = $response;
$this->config = $config->get('captchavel');
$this->reCaptchaFactory = $reCaptchaFactory;
$this->reCaptcha = $reCaptcha;
}

/**
Expand All @@ -80,7 +80,7 @@ public function handle($request, Closure $next, float $threshold = null)
}

/**
* Detect if the Request has been as a POST method
* Detect if the Request is a "write" method
*
* @param \Illuminate\Http\Request $request
* @return bool
Expand Down Expand Up @@ -127,12 +127,12 @@ protected function hasValidReCaptcha(Request $request, float $threshold)
*
* @param \Illuminate\Http\Request $request
* @param float $threshold
* @return \DarkGhostHunter\Captchavel\RecaptchaResponseHolder
* @return \DarkGhostHunter\Captchavel\ReCaptcha
*/
protected function resolve(Request $request, float $threshold)
{
return app('recaptcha')->setResponse(
$this->recaptchaFactory
return $this->reCaptcha->setResponse(
$this->reCaptchaFactory
->setExpectedAction($this->sanitizeAction($request->getRequestUri()))
->setScoreThreshold($threshold)
->verify($request->input('_recaptcha'), $request->getClientIp())
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Middleware/TransparentRecaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected function hasValidRequest(Request $request)
*
* @param \Illuminate\Http\Request $request
* @param float $threshold
* @return \DarkGhostHunter\Captchavel\RecaptchaResponseHolder
* @return \DarkGhostHunter\Captchavel\ReCaptcha
*/
protected function resolve(Request $request, float $threshold)
{
Expand Down
6 changes: 3 additions & 3 deletions src/RecaptchaResponseHolder.php → src/ReCaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Illuminate\Support\Carbon;
use ReCaptcha\Response;

class RecaptchaResponseHolder
class ReCaptcha
{
/**
* The reCAPTCHA response
Expand All @@ -32,7 +32,7 @@ class RecaptchaResponseHolder
* Sets the Recaptcha
*
* @param \ReCaptcha\Response $response
* @return \DarkGhostHunter\Captchavel\RecaptchaResponseHolder
* @return \DarkGhostHunter\Captchavel\ReCaptcha
*/
public function setResponse(Response $response)
{
Expand Down Expand Up @@ -65,7 +65,7 @@ public function getThreshold()
* Sets the Threshold
*
* @param float $threshold
* @return \DarkGhostHunter\Captchavel\RecaptchaResponseHolder
* @return \DarkGhostHunter\Captchavel\ReCaptcha
*/
public function setThreshold(float $threshold)
{
Expand Down
Loading

0 comments on commit f4863c0

Please sign in to comment.