This repository has been archived by the owner on Nov 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSlim2CSRFProtection.php
64 lines (50 loc) · 1.93 KB
/
Slim2CSRFProtection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
/**
* CSRF protection for Slim framework (version 2)
* https://github.com/komaval/SlimCSRFProtection/wiki
* @author komaval
*/
class Slim2CSRFProtection extends \Slim\Middleware {
public static function get_token() {
if( isset($_SESSION['csrf_token']) ) return $_SESSION['csrf_token'];
$token = md5( microtime() . rand() . uniqid() );
return $token;
}
public function __construct($onerror = false) {
if($onerror && is_callable($onerror)) {
$this->_onerror = $onerror;
}
}
public function call() {
$this->app->hook('slim.before', array($this, 'check'));
$this->next->call();
}
public function is_token_valid($usertoken) {
return $usertoken === $_SESSION['csrf_token'];
}
public function check() {
if(!isset($_SESSION)) {
$this->app->halt(400, "SlimCSRFProtection: session not started.");
}
$env = $this->app->environment();
$usertoken = $env['X_CSRF_TOKEN'] ?: $this->app->request()->post( 'csrf_token' );
if( in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE')) ) {
if ( !$this->is_token_valid($usertoken) ) {
if(property_exists($this, '_onerror')) {
call_user_func($this->_onerror);
} else {
$this->app->halt(400, "CSRF protection: wrong token");
}
}
}
$token = static::get_token();
$_SESSION['csrf_token'] = $token;
$this->app->view()->setData(array(
'csrf_token' => $token,
'csrf_protection_input' => '<input type="hidden" name="csrf_token" value="' . $token . '"/>',
'csrf_protection_jquery' =>
'<script type="text/javascript">$(document).ajaxSend(function(e,xhr){xhr.setRequestHeader("X-CSRF-Token","' . $token . '");});</script>'
));
}
}
?>