-
Notifications
You must be signed in to change notification settings - Fork 0
/
Csrf.php
70 lines (64 loc) · 1.57 KB
/
Csrf.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
65
66
67
68
69
70
<?php
namespace alvin\phpmvc;
/**
* Middleware for csrf protection
*/
class Csrf {
/**
* Configuration array
* @var array
*/
private array $config = [
"lookInCookie" => false,
];
/**
* Creates a csrf middleware object and sets configs.
*
* @param array $config
*/
public function __construct(array $config) {
foreach ($config as $key => $value) {
$this->config[$key] = $value;
}
}
/**
* Verify incoming csrf tokens
*
* @param string $token
* @return boolean
*/
public static function verify($token = "") {
return hash_equals($_SESSION['csrfToken'], $token);
}
/**
* The function to run when this middleware is invoked.
*
* @param Request $request alvin\phpmvc\Request object
* @param Response $response alvin\phpmvc\Response object
* @param callabe $next next middleware to execute
* @return any
*/
public function __invoke(Request $request, Response $response, $next) {
$route = $request->getRoute();
$httpMethod = $request->getMethod();
if ($httpMethod == "get") {
return $next();
}
if (in_array($route, $this->config['ignore'])) {
return $next();
}
if (!isset($_COOKIE['XSRF_TOKEN']) || !$request->input('_csrf')) {
return $response->send("invalid csrf token");
}
$lookInCookie = $this->config['lookInCookie'];
$incomingToken = $lookInCookie ? $_COOKIE['XSRF_TOKEN'] : $request->input('_csrf');
if (!$incomingToken) {
return $response->send("invalid csrf token");
}
$isValid = $this->verify($incomingToken);
if (!$isValid) {
return $response->send("invalid csrf token");
}
return $next();
}
}