Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

Commit

Permalink
use StringUtils for csrf filter. add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
anlutro committed Nov 14, 2014
1 parent 822d505 commit b74d395
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Web/Filters/CsrfFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Illuminate\Routing\Route;
use Illuminate\Session\Store;
use Illuminate\Session\TokenMismatchException;
use Symfony\Component\Security\Core\Util\StringUtils;

class CsrfFilter
{
Expand All @@ -27,7 +28,7 @@ public function __construct(Store $session, $regenerate = true)

public function filter(Route $route, Request $request)
{
if ($this->session->token() != $request->input('_token')) {
if (!StringUtils::equals($this->session->token(), $request->input('_token'))) {
throw new TokenMismatchException;
}

Expand Down
69 changes: 69 additions & 0 deletions tests/Web/Filters/CsrfFilterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

use Mockery as m;
use Illuminate\Http\Request;

class CsrfFilterTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}

public function makeFilter($session, $regenerate)
{
return new \anlutro\Core\Web\Filters\CsrfFilter($session, $regenerate);
}

public function mockSession()
{
return m::mock('Illuminate\Session\Store');
}

public function mockRoute()
{
return m::mock('Illuminate\Routing\Route');
}

/**
* @test
* @dataProvider getTokenData
*/
public function throwsExceptionWhenTokensAreNotEqual($throws, $input, $sessionToken)
{
$route = $this->mockRoute();
$request = Request::create('/', 'POST', ['_token' => $input]);
$session = $this->mockSession();
$session->shouldReceive('token')->andReturn($sessionToken);
$filter = $this->makeFilter($session, false);
if ($throws) {
$this->setExpectedException('Illuminate\Session\TokenMismatchException');
}
$filter->filter($route, $request);
}

public function getTokenData()
{
return [
[true, 'foo', 'bar'],
[true, '', 'bar'],
[true, '', '0asdf'],
[true, 0, '0asdf'],
[true, 0, 'foo'],
[true, 1, '1asdf'],
[false, '0asdf', '0asdf'],
];
}

/** @test */
public function regeneratesTokenWhenConfigured()
{
$route = $this->mockRoute();
$request = Request::create('/', 'POST', ['_token' => 'asdf']);
$session = $this->mockSession();
$session->shouldReceive('token')->andReturn('asdf');
$session->shouldReceive('regenerateToken')->once();
$filter = $this->makeFilter($session, true);
$filter->filter($route, $request);
}
}

0 comments on commit b74d395

Please sign in to comment.