mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-07-11 00:12:28 +00:00
[FEATURE] Csrf token
- Added functionality to CsrfToken class. - Added header support to Request class. - Added option to set BaseCsrfVerifier class in RouterBase and SimpleRouter.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
use Pecee\CsrfToken;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\RouterException;
|
||||
|
||||
class BaseCsrfVerifier extends Middleware {
|
||||
|
||||
const POST_KEY = 'csrf-token';
|
||||
const HEADER_KEY = 'X-CSRF-TOKEN';
|
||||
|
||||
public function handle(Request $request) {
|
||||
|
||||
if($request->getMethod() != 'get') {
|
||||
|
||||
$token = (isset($_POST[self::POST_KEY])) ? $_POST[self::POST_KEY] : null;
|
||||
|
||||
// If the token is not posted, check headers for valid x-csrf-token
|
||||
if($token === null) {
|
||||
$token = $request->getHeader(self::HEADER_KEY);
|
||||
}
|
||||
|
||||
$tokenValidator = new CsrfToken();
|
||||
if( !$tokenValidator->validate( $token ) ) {
|
||||
throw new RouterException('Invalid csrf-token.');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,5 @@ use Pecee\SimpleRouter\RouterEntry;
|
||||
|
||||
abstract class Middleware
|
||||
{
|
||||
public function handle(Request $request) {
|
||||
return true;
|
||||
}
|
||||
abstract function handle(Request $request);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware {
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -6,11 +6,13 @@ class Request {
|
||||
protected $uri;
|
||||
protected $host;
|
||||
protected $method;
|
||||
protected $headers;
|
||||
|
||||
public function __construct() {
|
||||
$this->host = $_SERVER['HTTP_HOST'];
|
||||
$this->uri = rtrim($_SERVER['REQUEST_URI'], '/') . '/';
|
||||
$this->method = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
|
||||
$this->headers = getallheaders();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,4 +52,21 @@ class Request {
|
||||
return (isset($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW']: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get headers
|
||||
* @return array
|
||||
*/
|
||||
public function getHeaders() {
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get header value by name
|
||||
* @param string $name
|
||||
* @return string|null
|
||||
*/
|
||||
public function getHeader($name) {
|
||||
return (isset($this->headers[$name])) ? $this->headers[$name] : null;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user