turnstile via cloudflare working i believe
CI / testsuite (mysql, 8.2, ) (push) Successful in 3m21s
CI / testsuite (mysql, 8.4, ) (push) Successful in 4m19s
CI / testsuite (pgsql, 8.2, ) (push) Successful in 3m7s
CI / testsuite (pgsql, 8.4, ) (push) Successful in 4m19s
CI / testsuite (sqlite, 8.2, ) (push) Successful in 3m10s
CI / testsuite (sqlite, 8.2, prefer-lowest) (push) Successful in 3m4s
CI / testsuite (sqlite, 8.4, ) (push) Successful in 4m20s
CI / Coding Standard & Static Analysis (push) Failing after 2m3s

This commit is contained in:
bs
2026-11-11 02:41:55 -08:00
parent 447cbf5800
commit 6e34d9a65a
5 changed files with 292 additions and 77 deletions
+6 -2
View File
@@ -8,13 +8,13 @@ return [
'email' => true,
'captcha' => true,
],
'clientIpHeader' => '',
'clientIpHeader' => null,
'email' => [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => true, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => true,
'to' => 'bshipley@hipowered.dev',
'to' => 'contact@hipowered.dev',
'cc' => '', // email string or array of emails
'bcc' => '', // email string or array of emails
],
@@ -26,5 +26,9 @@ return [
'controller' => 'ContactUsFormSubmissions',
'action' => 'view',
],
'turnstile' => [
'siteKey' => '{SITE_KEY_GOES_HERE}', // define in app_local or an .env variable
'secretKey' => '{SECRET_GOES_HERE}', // define in app_local or an .env variable
],
],
];
+2 -2
View File
@@ -18,12 +18,12 @@ class CakeContactUsPlugin extends BasePlugin {
/**
* @var string
*/
public const EVENT_BEFORE_CONTACT_US_FORM_SAVED = 'ContactUs.Global.beforeRegister';
public const EVENT_BEFORE_CONTACT_US_FORM_SAVED = 'ContactUs.Global.beforeSave';
/**
* @var string
*/
public const EVENT_AFTER_CONTACT_US_FORM_SAVED = 'ContactUs.Global.afterRegister';
public const EVENT_AFTER_CONTACT_US_FORM_SAVED = 'ContactUs.Global.afterSave';
/**
* @var string
+174 -26
View File
@@ -6,6 +6,7 @@ namespace CakeContactUs\Controller\Component;
use Cake\Controller\Component;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\Http\Response;
use Cake\I18n\DateTime;
use Cake\ORM\Table;
@@ -37,6 +38,37 @@ class ContactUsComponent extends Component {
*/
protected array $components = ['Flash'];
/**
* Get the Controller callbacks this Component is interested in.
*
* Uses Conventions to map controller events to standard component
* callback method names. By defining one of the callback methods a
* component is assumed to be interested in the related event.
*
* Override this method if you need to add non-conventional event listeners.
* Or if you want components to listen to non-standard events.
*
* @return array<string, mixed>
*/
public function implementedEvents(): array {
$eventMap = [
'Controller.initialize' => 'beforeFilter',
'Controller.startup' => 'startup',
'Controller.beforeRender' => 'beforeRender',
'Controller.beforeRedirect' => 'beforeRedirect',
'Controller.shutdown' => 'afterFilter',
CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED => 'beforeFormSaved',
];
$events = [];
foreach ($eventMap as $event => $method) {
if (method_exists($this, $method)) {
$events[$event] = $method;
}
}
return $events;
}
/**
* @param array $config
* @throws \Exception
@@ -49,13 +81,18 @@ class ContactUsComponent extends Component {
$this->ContactUsFormSubmissions = TableRegistry::getTableLocator()->get('CakeContactUs.ContactUsFormSubmissions');
$requireCaptcha = Configure::readOrFail('ContactUs.fields.captcha');
$useTurnstile = Configure::read('ContactUs.turnstile', []);
$this->setConfig('redirectUrl', Configure::read('ContactUs.redirectUrl', '/'));
$this->setConfig('addIdToRedirect', Configure::read('ContactUs.addIdToRedirect', false));
$this->setConfig('requireEmail', Configure::readOrFail('ContactUs.fields.email'));
$this->setConfig('requireCaptcha', $requireCaptcha);
$this->setConfig('turnstile', $useTurnstile);
if ($requireCaptcha) {
$this->getController()->viewBuilder()->addHelpers(['Captcha.Captcha']);
}
if ($useTurnstile) {
// $this->getController()->viewBuilder()->addHelpers(['']);
}
}
/**
@@ -78,46 +115,51 @@ class ContactUsComponent extends Component {
if (!isset($postData)) {
$postData = $this->getController()->getRequest()->getData();
}
$postData['client_ip'] = $postData['client_ip'] ??
($this->getConfig('clientIpHeader') ?
$this->getController()->getRequest()->getHeaderLine($this->getConfig('clientIpHeader')) :
$this->getController()->getRequest()->clientIp()
);
$postData['client_ip'] = $this->_getIp();
$postData['submitted_at'] = DateTime::now();
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData);
$this->getController()->set(['contactUsFormSubmission' => $contactUsFormSubmission]);
$event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED, [
'contactUsFormSubmission' => $contactUsFormSubmission,
], $this->getController());
$result = $event->getResult();
if ($result instanceof EntityInterface) {
$postData = $result->toArray();
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData);
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission);
if ($contactUsFormSubmissionSaved) {
return $this->_afterFormSaved($contactUsFormSubmissionSaved);
}
// @TODO contact us form submission failed - handle here
}
if ($event->isStopped()) {
return $this->getController()->redirect($event->getResult());
}
if (!$postData) {
if ($result['redirect'] ?? false) {
return $this->getController()->redirect($result['redirect']);
}
$message = __d('cake_contact_us', 'Verification failed. Please try again.');
$this->Flash->error($message);
return;
}
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData);
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission);
if ($result instanceof EntityInterface) {
$final = $this->_finishSave($contactUsFormSubmission);
if ($final instanceof EntityInterface) { // validation failed
$this->getController()->set(['contactUsFormSubmission' => $final]);
if ($contactUsFormSubmissionSaved) {
return $this->_afterFormSaved($contactUsFormSubmissionSaved);
return;
}
return $final;
}
$message = __d('cake_contact_us', 'Something doesn\'t look quite right. Please try again.');
$this->Flash->error($message);
$final = $this->_finishSave($contactUsFormSubmission);
if ($final instanceof EntityInterface) {
// @TODO contact us form submission failed - handle here
$message = __d('cake_contact_us', 'Something doesn\'t look quite right. Please try again.');
// @TODO contact us form submission failed - handle here
$this->getController()->set(['contactUsFormSubmission' => $contactUsFormSubmission]);
$this->Flash->error($message);
// @TODO contact us form submission failed - handle here
$this->getController()->set(['contactUsFormSubmission' => $final]);
return;
}
return $final;
}
/**
@@ -145,4 +187,110 @@ class ContactUsComponent extends Component {
return $this->getController()->redirect($redirectUrl);
}
/**
* @return void
*/
public function beforeFormSaved(EventInterface $event) {
if (!$this->getConfig('turnstile')) {
return;
}
if (!$this->getConfig('turnstile.siteKey') || !$this->getConfig('turnstile.secretKey')) {
$event->stopPropagation();
$event->setResult([
'success' => false,
'error-codes' => ['missing-turnstile-site-configuration'],
]);
return;
}
$entity = $event->getData('contactUsFormSubmission');
$token = $entity->get('cf-turnstile-response') ?: $this->getController()->getRequest()->getData('cf-turnstile-response');
if (!$token) {
$event->stopPropagation();
$event->setResult([
'success' => false,
'error-codes' => ['missing-token'],
]);
return;
}
$turnstileValidation = $this->_validateTurnstile(
$token,
$entity->get('client_ip') ?? $this->_getIp(),
);
if ($turnstileValidation['success'] ?? false) {
return; // good to proceed
}
$event->stopPropagation();
$event->setResult($turnstileValidation);
}
/**
* @return string -
*/
protected function _getIp() {
if ($this->getConfig('clientIpHeader')) {
return $this->getController()->getRequest()->getHeaderLine($this->getConfig('clientIpHeader')) ?:
$this->getController()->getRequest()->clientIp();
}
return $this->getController()->getRequest()->clientIp();
}
/**
* @param \Cake\Datasource\EntityInterface $contactUsFormSubmission
*
* @return \Cake\Datasource\EntityInterface|\Cake\Http\Response
*/
protected function _finishSave(EntityInterface $contactUsFormSubmission) {
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission);
if ($contactUsFormSubmissionSaved) {
return $this->_afterFormSaved($contactUsFormSubmissionSaved);
}
return $contactUsFormSubmission; // has errors - return entity
}
/**
* @param string $token
* @param string|null $remoteIp
*
* @return array
*/
protected function _validateTurnstile(string $token, string|null $remoteIp = null): array {
// if (PHP_SAPI === 'cli') {
// return ['success' => true];
// }
$url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
$data = [
'secret' => $this->getConfig('turnstile.secretKey'),
'response' => $token,
];
if ($remoteIp) {
$data['remoteip'] = $remoteIp;
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($response === false || $error !== '') {
return ['success' => false, 'error-codes' => ['internal-error']];
}
return json_decode($response, true);
}
}
@@ -6,7 +6,6 @@ namespace CakeContactUs\Test\TestCase\Controller;
use Cake\Core\Configure;
use Cake\Event\EventList;
use Cake\Event\EventManager;
use Cake\Mailer\Transport\DebugTransport;
use Cake\TestSuite\EmailTrait;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
@@ -89,7 +88,7 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
*
* Tests a POST request to the add action with a logged in user
*
* @throws Exception
* @throws \Exception
*
* @return void
*/
@@ -110,6 +109,7 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
$this->assertResponseCode(302);
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertNoMailSent();
}
@@ -119,28 +119,92 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
*
* Tests a POST request to the add action with a logged in user
*
* @throws Exception
* @throws \Exception
*
* @return void
*/
public function testAddPostSuccessWithTurnstile(): void {
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
Configure::write('ContactUs.turnstile', [
'siteKey' => '1x00000000000000000000AA',
'secretKey' => '1x0000000000000000000000000000000AA',
]);
$url = [
'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions',
'action' => 'add',
];
$data = [
'first_name' => 'valid name',
'email' => 'valid_email@test.com',
'message' => 'valid message goes here',
'cf-turnstile-response' => 'XXXX.DUMMY.TOKEN.XXXX',
];
$this->post($url, $data);
$this->assertResponseCode(302);
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertNoMailSent();
}
/**
* Test add method
*
* Tests a POST request to the add action with a logged in user
*
* @throws \Exception
*
* @return void
*/
public function testAddPostInvalidTurnstile(): void {
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
Configure::write('ContactUs.turnstile', [
'siteKey' => '2x00000000000000000000BB',
'secretKey' => '2x0000000000000000000000000000000AA',
]);
$url = [
'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions',
'action' => 'add',
];
$data = [
'first_name' => 'valid name',
'email' => 'valid_email@test.com',
'message' => 'valid message goes here',
'cf-turnstile-response' => 'XXXX.DUMMY.TOKEN.XXXX',
];
$this->post($url, $data);
$this->assertResponseCode(200);
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertNoMailSent();
}
/**
* Test add method
*
* Tests a POST request to the add action with a logged in user
*
* @throws \Exception
*
* @return void
*/
public function testAddPostSuccessBothEmailsSent(): void {
Configure::write('ContactUs', [
'fields' => [
'captcha' => false,
'email' => true,
],
'email' => [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => true, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => true,
'to' => 'test@example.com',
],
],
Configure::write('ContactUs.fields', [
'captcha' => false,
'email' => true,
]);
Configure::write('EmailTransport', [
'default' => [
'className' => DebugTransport::class,
Configure::write('ContactUs.email', [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => true, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => true,
'to' => 'test@example.com',
],
]);
@@ -161,6 +225,7 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertMailCount(2); // confirmation + backend emails
@@ -171,23 +236,21 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
*
* Tests a POST request to the add action with a logged in user
*
* @throws Exception
* @throws \Exception
*
* @return void
*/
public function testAddPostSuccessConfirmationEmailSent(): void {
Configure::write('ContactUs', [
'fields' => [
'captcha' => false,
'email' => true,
],
'email' => [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => true, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => false,
'to' => 'test@example.com',
],
Configure::write('ContactUs.fields', [
'captcha' => false,
'email' => true,
]);
Configure::write('ContactUs.email', [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => true, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => false,
'to' => 'test@example.com',
],
]);
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
@@ -207,6 +270,7 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertMailCount(1); // confirmation only
@@ -217,23 +281,17 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
*
* Tests a POST request to the add action with a logged in user
*
* @throws Exception
* @throws \Exception
*
* @return void
*/
public function testAddPostSuccessBackendEmailSent(): void {
Configure::write('ContactUs', [
'fields' => [
'captcha' => false,
'email' => true,
],
'email' => [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => false, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => true,
'to' => 'test@example.com',
],
Configure::write('ContactUs.email', [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => false, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => true,
'to' => 'test@example.com',
],
]);
@@ -259,6 +317,7 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertMailCount(1); // backend email only
@@ -269,7 +328,7 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
*
* Tests a POST request to the add action with a logged in user
*
* @throws Exception
* @throws \Exception
*
* @return void
*/
@@ -289,7 +348,6 @@ class ContactUsFormSubmissionsControllerTest extends TestCase {
];
$this->post($url, $data);
$this->assertResponseCode(200);
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
+5
View File
@@ -72,6 +72,11 @@ Configure::write('ContactUs', [
'to' => 'test@example.com',
],
],
'turnstile' => false,
// 'turnstile' => [
// 'siteKey' => '1x00000000000000000000AA',
// 'secretKey' => '1x0000000000000000000000000000000AA',
// ],
]);
Configure::write('EmailTransport', [
'default' => [