Perform CSRF filter on all post, put, patch and delete requests

Submitted by mhanson01 - 10 years ago

Perform CSRF filter on all post, put, patch, and delete requests through constructor of the BaseController.

class BaseController extends Controller {

    // Be sure to call parent::__construct() when needed
    public function __construct()
    {
        // Perform CSRF check on all post/put/patch/delete requests
        $this->beforeFilter('csrf', array('on' => array('post', 'put', 'patch', 'delete')));
    }

	/**
	 * Setup the layout used by the controller.
	 *
	 * @return void
	 */
	protected function setupLayout()
	{
		if ( ! is_null($this->layout))
		{
			$this->layout = View::make($this->layout);
		}
	}

}

// END BASE CONTROLLER

/**************  QUICK AND DIRTY TESTING **************/

// Add to routes file
Route::controller('testtoken', 'TestTokenController');

// Within TestTokenController.php place...
class TestTokenController extends BaseController {

    // http://localhost/testtoken/token
    public function getToken()
	{
		$form  = Form::open(['url' => '/testtoken/result']);
		$form .= Form::submit('Submit Form With Token');
		$form .= Form::close();

		return $form;
	}

    // http://localhost/testtoken/no-token
	public function getNoToken()
	{
		$form  = '<form method="post" action="/testtoken/result">';
		$form .= Form::submit('Submit Form Without Token');
		$form .= Form::close();

		return $form;
	}

    // http://localhost/testtoken/bad-token
	public function getBadToken()
	{
		$form  = '<form method="post" action="/testtoken/result">';
		$form .= '<input type="hidden" name="_token" value="BadToken">';
		$form .= Form::submit('Submit Form With Bad Token');
		$form .= Form::close();

		return $form;
	}

	public function postResult()
	{
		return 'Token found!';
	}

}