Skip to content

Commit

Permalink
Upgrade mzur/kirby-form
Browse files Browse the repository at this point in the history
Checking the CSRF token is now done by kirby-form. It also offers
a new optional second constructor argument for multiple forms on
one page.

Closes #119
  • Loading branch information
mzur committed Feb 5, 2017
1 parent 61f8e85 commit f916212
Show file tree
Hide file tree
Showing 48 changed files with 689 additions and 289 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
},
"require": {
"php": ">=5.5.0",
"mzur/kirby-form": "^0.1.0"
"mzur/kirby-form": "^1.0"
},
"require-dev": {
"getkirby/toolkit": "dev-master"
Expand Down
4 changes: 2 additions & 2 deletions docs/actions/email-select.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ This action can choose the `to` email address for the email action based on the

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
Expand Down
4 changes: 2 additions & 2 deletions docs/actions/email.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ If there is an `email` field in the form data, the action will use it as `replyT

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
Expand Down
4 changes: 2 additions & 2 deletions docs/actions/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ This action appends the form data and some information on the submitter to a log

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
Expand Down
4 changes: 2 additions & 2 deletions docs/actions/login.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ This action provides a simple way of logging in to the Kirby frontend. For this

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'username' => [
'rules' => ['required'],
Expand Down
4 changes: 2 additions & 2 deletions docs/actions/session-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ This example stores the the form data in the session and redirects the user to a

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
Expand Down
4 changes: 2 additions & 2 deletions docs/actions/webhook.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ This example calls the MailChimp API to add an email address to a list.

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email_address' => [
'rules' => ['required', 'email'],
Expand Down
32 changes: 32 additions & 0 deletions docs/answers.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,35 @@ if (r::is('POST')) {
## Can I work with the submitted form data outside of Uniform snippets?

Sure, since the form data is submitted with an ordinary `POST` request you can access the value of a field with name `myfield` anywhere in your code using the [`get` Kirby helper](https://getkirby.com/docs/cheatsheet/helpers/get) `get('myfield')`. If you have access to the `$form` object, you can use the [data method](methods#datakey-value), too.

## I have multiple static forms on one page. When one fails the error messages are also displayed for the other forms. Why?

This happens because the forms share the same session storage by default. In this case you have to give each form a unique session storage. You can do that with the second parameter of the `Form` constructor:

```php
<?php

use Uniform\Form;

return function ($site, $pages, $page)
{
$contactForm = new Form([/* rules */], 'contact-form');
$newsletterForm = new Form([/* rules */], 'newsletter-form');

if (r::is('POST')) {
if (/* contact form sent */) {
$contactForm->emailAction([
'to' => '[email protected]',
'from' => '[email protected]',
]);
} elseif (/* newsletter form sent */) {
$newsletterForm->emailAction([
'to' => '[email protected]',
'from' => '[email protected]',
]);
}
}

return compact('form');
};
```
4 changes: 2 additions & 2 deletions docs/examples/basic.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ This is an example for a very basic form that asks the user to enter an email ad

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/extended.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ If the form is successfully validated, the content is sent via email to the owne

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'name' => [
'rules' => ['required'],
Expand Down
2 changes: 1 addition & 1 deletion docs/methods.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Methods

These are only the most important methods of `Uniform\Form`. For all methods check the [source](https://github.com/mzur/kirby-uniform/blob/master/src/Form.php). Be sure to [check out](https://github.com/jevets/kirby-form) `Jevets\Kirby\Form`, too, which is the base class of `Uniform\Form`.
These are only the most important methods of `Uniform\Form`. For all methods check the [source](https://github.com/mzur/kirby-uniform/blob/master/src/Form.php). Be sure to [check out](https://github.com/mzur/kirby-form) `Jevets\Kirby\Form`, too, which is the base class of `Uniform\Form`.

## old($key)

Expand Down
4 changes: 2 additions & 2 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ Uniform is initialized in the page controller like this:

use Uniform\Form;

return function ($site, $pages, $page) {

return function ($site, $pages, $page)
{
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
Expand Down
8 changes: 0 additions & 8 deletions src/Exceptions/TokenMismatchException.php

This file was deleted.

52 changes: 13 additions & 39 deletions src/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Uniform;

use R;
use Str;
use Redirect;
use C as Config;
Expand All @@ -13,17 +12,9 @@
use Uniform\Exceptions\Exception;
use Jevets\Kirby\Form as BaseForm;
use Uniform\Exceptions\PerformerException;
use Uniform\Exceptions\TokenMismatchException;

class Form extends BaseForm
{
/**
* Name of the form field containing the CSRF token.
*
* @var string
*/
const CSRF_FIELD = 'csrf_token';

/**
* Indicates whether the validation should still be done
*
Expand Down Expand Up @@ -74,11 +65,12 @@ class Form extends BaseForm
* Create a new instance
*
* @param array $rules Form fields and their validation rules
* @param string $sessionKey Optional unique session key for multiple forms on the same page
* @return void
*/
function __construct($rules = [])
function __construct($rules = [], $sessionKey = null)
{
parent::__construct($rules);
parent::__construct($rules, $sessionKey);
static::loadTranslation();
$this->shouldValidate = true;
$this->shouldCallGuard = true;
Expand Down Expand Up @@ -153,16 +145,6 @@ public function success()
return $this->success;
}

/**
* Save the form data to the session
*/
public function saveData()
{
if ($this->shouldFlash) {
parent::saveData();
}
}

/**
* Validate the form data
*
Expand All @@ -172,14 +154,6 @@ public function validate()
{
$this->shouldValidate = false;

if (csrf(R::postData(self::CSRF_FIELD)) !== true) {
if (Config::get('debug') === true) {
throw new TokenMismatchException('The CSRF token was invalid.');
}

$this->fail();
}

if (parent::validates()) {
$this->success = true;
} else {
Expand Down Expand Up @@ -248,16 +222,6 @@ public function action($action, $options = [])
return $this;
}

/**
* Forget a form field
*
* @param string $key Form field name
*/
public function forget($key)
{
unset($this->data[$key]);
}

/**
* Call actions and gards as magic method.
*
Expand Down Expand Up @@ -289,6 +253,16 @@ public function __call($method, $parameters = [])
}
}

/**
* Save the form data to the session
*/
protected function saveData()
{
if ($this->shouldFlash) {
parent::saveData();
}
}

/**
* Redirect back to the page of the form
*/
Expand Down
2 changes: 1 addition & 1 deletion src/Guards/CalcGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class CalcGuard extends Guard
/**
* {@inheritDoc}
* Check if the captcha field was filled in correctly
* Remove the field from the form data if it was empty.
* Remove the field from the form data if it was correct.
*/
public function perform()
{
Expand Down
22 changes: 0 additions & 22 deletions src/helpers.php
Original file line number Diff line number Diff line change
@@ -1,30 +1,8 @@
<?php

use Uniform\Form;
use Uniform\Guards\CalcGuard;
use Uniform\Guards\HoneypotGuard;

if (!function_exists('csrf_field')) {
/**
* Generate a CSRF token form field.
*
* This function can be called multiple times and will reuse the same token during a
* single request.
*
* @param string $t The CSRF token to use. If empty a new one will be generated and reused for the duration of a request.
*
* @return string
*/
function csrf_field($t = null)
{
// remember the token for multipme function calls
static $token = null;
$token = $token ?: csrf();
// the token parameter overrides the generated token
return '<input type="hidden" name="'.Form::CSRF_FIELD.'" value="'.($t ?: $token).'">';
}
}

if (!function_exists('honeypot_field')) {
/**
* Generate a honeypot form field.
Expand Down
17 changes: 4 additions & 13 deletions tests/FormTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Uniform\Guards\Guard;
use Uniform\Actions\Action;
use Uniform\Exceptions\Exception;
use Uniform\Exceptions\TokenMismatchException;
use Jevets\Kirby\Exceptions\TokenMismatchException;

class FormTest extends TestCase
{
Expand All @@ -21,16 +21,6 @@ public function setUp()
$this->form = new FormStub;
}

public function testAddErrors()
{
$this->form->addErrors(['email' => 'Not set']);
$this->assertEquals(['email' => ['Not set']], $this->form->errors());
$this->form->addErrors(['email' => 'No email']);
$this->assertEquals(['email' => ['Not set', 'No email']], $this->form->errors());
$this->form->addErrors(['email' => ['another', 'error']]);
$this->assertEquals(['email' => ['Not set', 'No email', 'another', 'error']], $this->form->errors());
}

public function testValidateCsrfException()
{
$this->setExpectedException(TokenMismatchException::class);
Expand Down Expand Up @@ -237,8 +227,9 @@ public function testWithoutFlashing()
$this->form->withoutFlashing();
$this->form->saveData();
$this->form->addError('email', 'error message');
$this->assertEmpty(Flash::get(Form::FLASH_KEY_DATA));
$this->assertEmpty(Flash::get(Form::FLASH_KEY_ERRORS));
$flash = Flash::getInstance();
$this->assertEmpty($flash->get(Form::FLASH_KEY_DATA));
$this->assertEmpty($flash->get(Form::FLASH_KEY_ERRORS));
}
}

Expand Down
8 changes: 0 additions & 8 deletions tests/HelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,8 @@ class HelperTest extends TestCase
{
public function testFunction()
{
$this->assertTrue(function_exists('csrf_field'));
$this->assertTrue(function_exists('honeypot_field'));
$this->assertTrue(function_exists('uniform_captcha'));
$this->assertTrue(function_exists('captcha_field'));
}

public function testCsrfField()
{
// the token should not be regenerated during a single request
$this->assertEquals(csrf_field(), csrf_field());
$this->assertContains('value="abc"', csrf_field('abc'));
}
}
5 changes: 3 additions & 2 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ class TestCase extends \PHPUnit_Framework_TestCase
public function setUp()
{
parent::setUp();
Flash::set(Form::FLASH_KEY_DATA, null);
Flash::set(Form::FLASH_KEY_ERRORS, null);
$flash = Flash::getInstance();
$flash->set(Form::FLASH_KEY_DATA, null);
$flash->set(Form::FLASH_KEY_ERRORS, null);
$_POST = [];
}
}
2 changes: 1 addition & 1 deletion vendor/composer/autoload_files.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
$baseDir = dirname($vendorDir);

return array(
'e862d9fce5eaa28c798b151ac7fc8bc6' => $vendorDir . '/mzur/kirby-flash/src/helpers.php',
'f485627b283286104bbc2461f512799f' => $vendorDir . '/getkirby/toolkit/bootstrap.php',
'e862d9fce5eaa28c798b151ac7fc8bc6' => $vendorDir . '/mzur/kirby-flash/src/helpers.php',
'316f57472eecfe71b6733d9d2acbcae9' => $vendorDir . '/mzur/kirby-form/src/helpers.php',
'1f7ddc2baab73fdd75a4663f7a275bb1' => $baseDir . '/src/helpers.php',
'ae86d24018d4ff2f7d0f86beff02023f' => $baseDir . '/index.php',
Expand Down
2 changes: 1 addition & 1 deletion vendor/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
class ComposerStaticInit8752c63a2ba4ba7bb6bd13381d5cdc05
{
public static $files = array (
'e862d9fce5eaa28c798b151ac7fc8bc6' => __DIR__ . '/..' . '/mzur/kirby-flash/src/helpers.php',
'f485627b283286104bbc2461f512799f' => __DIR__ . '/..' . '/getkirby/toolkit/bootstrap.php',
'e862d9fce5eaa28c798b151ac7fc8bc6' => __DIR__ . '/..' . '/mzur/kirby-flash/src/helpers.php',
'316f57472eecfe71b6733d9d2acbcae9' => __DIR__ . '/..' . '/mzur/kirby-form/src/helpers.php',
'1f7ddc2baab73fdd75a4663f7a275bb1' => __DIR__ . '/../..' . '/src/helpers.php',
'ae86d24018d4ff2f7d0f86beff02023f' => __DIR__ . '/../..' . '/index.php',
Expand Down
Loading

0 comments on commit f916212

Please sign in to comment.