Skip to content

Commit 73c5962

Browse files
committed
Added constructor parameter to toggle whether the CSRFGuard should be graceful or not. If graceful the session is destroyed, if not (the default) then the application is halted with a 404 HTTP status code.
1 parent 1a805c4 commit 73c5962

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

Middleware/CsrfGuard.php

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,34 @@
44
class CsrfGuard extends \Slim\Middleware
55
{
66
/**
7-
* CSRF token key.
7+
* CSRF token key name.
88
*
99
* @var string
1010
*/
1111
protected $key;
1212

13+
/**
14+
* CSRF graceful.
15+
*
16+
* @var string
17+
*/
18+
protected $graceful;
19+
1320
/**
1421
* Constructor.
1522
*
16-
* @param string $key CSRF token key.
23+
* @param boolean $graceful If true then destroy the session (graceful), otherwise halt the application (ungraceful).
24+
* @param string $key The CSRF token key name.
1725
* @return void
1826
*/
19-
public function __construct($key = 'csrf_token')
27+
public function __construct($graceful = false, $key = 'csrf_token')
2028
{
2129
if (! is_string($key) || empty($key) || preg_match('/[^a-zA-Z0-9\-\_]/', $key)) {
2230
throw new \OutOfBoundsException('Invalid CSRF token key "' . $key . '"');
2331
}
2432

2533
$this->key = $key;
34+
$this->graceful = (bool) $graceful;
2635
}
2736

2837
/**
@@ -61,7 +70,11 @@ public function check() {
6170
if (in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE'))) {
6271
$userToken = $this->app->request()->post($this->key);
6372
if ($token !== $userToken) {
64-
session_destroy();
73+
if (! $this->graceful) {
74+
$this->app->halt(400, 'Invalid or missing CSRF token.');
75+
} else {
76+
session_destroy();
77+
}
6578
}
6679
}
6780

0 commit comments

Comments
 (0)