Hi,
I have a form with modelless forms and receive spam and I am working on prevent this spam.
I have made the following:
Contactcontroller
<?php
namespace App\Controller;
use App\Controller\AppController;
use App\Form\ContactForm;
use Cake\Core\Configure;
class ContactController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['index']);
}
public function index()
{
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->getData())) {
$this->Flash->success('We will get back to you soon.');
$this->redirect($this->referer());
} else {
$this->Flash->error('There was a problem submitting your form.');
}
}
$this->set('contact', $contact);
$this->set('recaptcha', Configure::read('Users.reCaptcha.key'));
}
}
?>
Then contactform.php
<?php
namespace App\Form;
use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Mailer\Email;
use Cake\Validation\Validator;
use CakeDC\Users\Controller\Traits\ReCaptchaTrait;
class ContactForm extends Form
{
use ReCaptchaTrait;
protected function _buildSchema(Schema $schema)
{
return $schema->addField('name', 'string')
->addField('email', ['type' => 'string'])
->addField('body', ['type' => 'text']);
}
protected function _buildValidator(Validator $validator)
{
$validator->add('name', 'length', [
'rule' => ['minLength', 10],
'message' => 'A name is required'
])->add('email', 'format', [
'rule' => 'email',
'message' => 'A valid email address is required',
])->add('body', 'length', [
'rule' => ['minlength', 20],
'message' => 'Message can not be empty'
])->add('g-recaptcha-response', 'custom', [
'rule' => function ($value, $context) {
if (!$value) {
return false;
}
if (!$this->validateReCaptcha($value,env('REMOTE_ADDR'))){
return false;
}
return true;
},
'message' => 'Need to use the recaptcha'
]);
return $validator;
}
protected function _execute(array $data)
{
$email = new Email('default');
$email->setFrom(['sales@website.com' => 'My Site'])
->setTo('sales@website.com')
->setSubject('Website')
->send('Ip: '.env('REMOTE_ADDR').', Name: '.$data['name'].', Email: '.$data['email'].' Message: '. $data['body']);
return true;
}
}
?>
I believe someone is submitting the form without going through the validation. Posting it directly? Am I doing something wrong here. I basicly used the Cakedc/Users RecaptchaTrait