Skip to content

Commit

Permalink
Merge pull request #18 from totov/master
Browse files Browse the repository at this point in the history
Allow plugin to verify requests and forward them on to other controller actions
  • Loading branch information
matt-west authored Jun 29, 2020
2 parents effb506 + 141d498 commit 059c1f3
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ if ($validates) {
}
```

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:

```twig
<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.
Expand Down
43 changes: 43 additions & 0 deletions src/controllers/RecaptchaController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace mattwest\craftrecaptcha\controllers;

use mattwest\craftrecaptcha\CraftRecaptcha;

use Craft;
use craft\web\Controller;
use yii\web\Response;

class RecaptchaController extends Controller
{
protected $allowAnonymous = true;

/**
* Handle verifying the submission and then pass it on to the relevant action (or not).
*/
public function actionVerifySubmission()
{
// ensure the request is a post
$this->requirePostRequest();

// grab the request object
$request = Craft::$app->getRequest();

// grab the intended action (required)
$action = $request->getRequiredParam('verified-action');

// grab the recaptcha response (required)
$captcha = $request->getRequiredParam('g-recaptcha-response');

// run these past the verify() function
$verified = CraftRecaptcha::$plugin->craftRecaptchaService->verify($captcha);

// if it's verified, then pass it on to the intended action, otherwise set a session error and return null
if ($verified) {
return Controller::run('/' . $action, func_get_args()); // run the intended action (add / to force it's scope to be outside the plugin) with all the params passed to this controller action
} else {
Craft::$app->getSession()->setError('Unable to verify your submission.');
return null;
}
}
}

0 comments on commit 059c1f3

Please sign in to comment.