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: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106:
<?php
namespace Coast;
use Coast\App\Access;
use Coast\App\Executable;
use Coast\Request;
use Coast\Response;
use Coast\Session;
class Csrf implements Executable, Access
{
use Access\Implementation;
use Executable\Implementation;
protected $_name = 'csrf';
protected $_methods = [
Request::METHOD_PUT,
Request::METHOD_POST,
Request::METHOD_DELETE,
];
public function __construct(array $options = array())
{
foreach ($options as $name => $value) {
if ($name[0] == '_') {
throw new \Coast\Exception("Access to '{$name}' is prohibited");
}
$this->$name($value);
}
}
public function name($name = null)
{
if (func_num_args() > 0) {
$this->_name = $name;
return $this;
}
return $this->_name;
}
public function methods(array $methods = null)
{
if (func_num_args() > 0) {
$this->_methods = $methods;
return $this;
}
return $this->_methods;
}
public function token()
{
if (!isset($_SESSION['__Coast\Csrf']['token'])) {
$_SESSION['__Coast\Csrf']['token'] = \Coast\pseudo_random();
}
return $_SESSION['__Coast\Csrf']['token'];
}
public function regenerate()
{
$_SESSION['__Coast\Csrf']['token'] = \Coast\pseudo_random();
return $this;
}
public function isValid($token, $throw = false)
{
if (!isset($_SESSION['__Coast\Csrf']['token'])) {
if ($throw) {
throw new Csrf\Exception('CSRF token not generated');
}
return false;
} else if ($token === null) {
if ($throw) {
throw new Csrf\Exception('CSRF token not provided');
}
return false;
} else if ($token !== $_SESSION['__Coast\Csrf']['token']) {
if ($throw) {
throw new Csrf\Exception('CSRF token invalid');
}
return false;
}
return true;
}
public function input()
{
return "<input type=\"hidden\" name=\"{$this->_name}\" value=\"{$this->token()}\">";
}
public function execute(Request $req, Response $res)
{
if (!in_array($req->method(), $this->_methods)) {
return;
}
$this->isValid($req->param($this->_name), true);
$req->param($this->_name, null);
$req->queryParam($this->_name, null);
$req->bodyParam($this->_name, null);
}
}