Note that there are some explanatory texts on larger screens.

plurals
  1. POfilter methods in a controller
    primarykey
    data
    text
    <p>I want to create a filter for my add, update, and delete actions in my controllers to automatically check if they</p> <ol> <li>were called in a POST, as opposed to GET or some other method</li> <li>and have the pageInstanceIDs which I set in the forms on my views <ul> <li>protects against xss</li> <li>protects against double submission of a form <ul> <li>from submit button double click</li> <li>from back button pressed after a submision</li> <li>from a url being saved or bookmarked </li> </ul></li> </ul></li> </ol> <p>Currently I extended \lithium\action\Controller using an AppController and have my add, update, and delete actions defined in there. I also have a boolean function in my AppController that checks if the appropriate pageInstanceIDs are in session or not.</p> <p>Below is my code:</p> <pre><code>public function isNotPostBack() { // pull in the session $pageInstanceIDs = Session::read('pageInstanceIDs'); $pageInstanceID = uniqid('', true); $this-&gt;set(compact('pageInstanceID')); $pageInstanceIDs[] = $pageInstanceID; Session::write('pageInstanceIDs', $pageInstanceIDs); // checks if this is a save operation if ($this-&gt;request-&gt;data){ $pageInstanceIDs = Session::read('pageInstanceIDs'); $pageIDIndex = array_search($this-&gt;request-&gt;data['pageInstanceID'], $pageInstanceIDs); if ($pageIDIndex !== false) { // remove the key unset($pageInstanceIDs[$pageIDIndex]); Session::write('pageInstanceIDs', $pageInstanceIDs); return true; } else return false; } else { return true; } } public function add() { if (!$this-&gt;request-&gt;is('post') &amp;&amp; exist($this-&gt;request-&gt;data())) { $msg = "Add can only be called with http:post."; throw new DispatchException($msg); } } </code></pre> <p>Then in my controllers I inherit from AppController and implement the action like so:</p> <pre><code>public function add() { parent::add(); if (parent::isNotPostBack()){ //do work } return $this-&gt;render(array('layout' =&gt; false)); } </code></pre> <p>which will ensure that the form used a POST and was <strong>not double submitted</strong> (back button or click happy users). This also helps protect against XSS.</p> <p>I'm aware there is a plugin for this, but I want to implement this as a filter so that my controller methods are cleaner. Implented this way, the only code in my actions are the //do work portion and the return statement.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload