Compare commits

...

22 Commits

Author SHA1 Message Date
Simon Sessingø 099f04fc10 Merge pull request #15 from skipperbent/development
[BUGFIX] Bugfixes and optimisations
2015-10-25 02:35:49 +02:00
Simon Sessingø ac2993f804 [BUGFIX] Bugfixes and optimisations
- When no parameter is recieved, router now returns null instead of empty
  string.
- json method in Response class now stops response after execution.
- Updated composer.json with correct autoload.
2015-10-25 02:34:25 +02:00
Simon Sessingø 99da70874e Merge pull request #14 from skipperbent/development
[BUGFIX] Fixed missing "/" in getRoute on some rare occasions.
2015-10-24 23:24:52 +02:00
Simon Sessingø 2a66350883 [BUGFIX] Fixed missing "/" in getRoute on some rare occasions. 2015-10-24 23:24:06 +02:00
Simon Sessingø c95a5291d3 Merge pull request #13 from skipperbent/development
[OPTIMISATION] getRoute optimisation
2015-10-24 23:21:23 +02:00
Simon Sessingø 20fc067765 [FEATURE] If no parameters are specified in the route, getRoute will now
add the parameters provided to the method instead.
2015-10-24 23:18:16 +02:00
Simon Sessingø cbb4294f58 Merge pull request #12 from skipperbent/development
[BUGFIX] Fixed getRoute method in SimpleRouter not being static.
2015-10-23 19:48:08 +02:00
Simon Sessingø d6bdcbe70c [BUGFIX] Fixed getRoute method in SimpleRouter not being static. 2015-10-23 19:34:27 +02:00
Simon Sessingø 25f569384f Merge pull request #11 from skipperbent/development
Development
2015-10-22 22:01:25 +02:00
Simon Sessingø b37c73d5dd [FEATURE] Added more features to Response class. 2015-10-22 21:42:33 +02:00
Simon Sessingø f5597c24ce [FEATURE] Added getInput method to return request items. 2015-10-22 21:13:54 +02:00
Simon Sessingø b8061f2aa7 [TASK] Added getUserAgent and getReferer methods to Request class. 2015-10-22 21:04:52 +02:00
Simon Sessingø 6c7ac2b250 [TASK] Added ip method to Response class. 2015-10-22 21:01:26 +02:00
Simon Sessingø d2de22e5e0 Merge pull request #10 from skipperbent/development
Development
2015-10-22 19:34:57 +02:00
Simon Sessingø 252fb16326 Merge branch 'development' of https://github.com/skipperbent/simple-php-router into development 2015-10-22 19:34:32 +02:00
Simon Sessingø 63dfbb24af [BUGFIX] Bugfix
- Fixed csrf-token cookie not being set on some paths.
- Changed RouterException in BaseCsrfVerifier to TokenMismatchException.
2015-10-22 19:33:20 +02:00
Simon Sessingø 3ccfac9422 Update README.md 2015-10-22 09:57:31 +02:00
Simon Sessingø 8f2d49fb73 Merge pull request #9 from skipperbent/development
[BUGFIX] Fixed missing / in beginning of url in getRoute when route d…
2015-10-22 00:18:28 +02:00
Simon Sessingø bdb5b2dead [BUGFIX] Fixed missing / in beginning of url in getRoute when route does not exist. 2015-10-22 00:17:49 +02:00
Simon Sessingø 5d643d842a Merge pull request #8 from skipperbent/feature-csrf
Custom CSRF middleware support
2015-10-21 19:15:22 +02:00
Simon Sessingø d6cf5c9b68 [TASK] Updated documentation 2015-10-21 19:14:37 +02:00
Simon Sessingø 03cac14e8e [FEATURE] Support for custom csrf verifier
- Added support for custom csrf verifier.
- Updated documentation.
2015-10-21 19:07:45 +02:00
9 changed files with 180 additions and 25 deletions
+39 -9
View File
@@ -33,7 +33,7 @@ Add the latest version pf Simple PHP Router to your ```composer.json```
- Global Constraints
- Sub-Domain Routing
- Optional/required parameters
- Required parameters
## Initialising the router
@@ -197,19 +197,49 @@ function csrf_token() {
}
```
### Example for getting the url
## Getting urls
In ```routes.php``` we have added this route:
**In ```routes.php``` we have added this route:**
```SimpleRouter::get('/item/{id}', 'myController@show', ['as' => 'item']);```
```php
SimpleRouter::get('/item/{id}', 'myController@show', ['as' => 'item']);
```
In the template we then call:
**In the template we then call:**
```url('item', ['id' => 22], ['category' => 'shoes']);```
```php
url('item', ['id' => 22], ['category' => 'shoes']);
```
Result url is:
**Result url is:**
```/item/22?category=shoes ```
```php
/item/22/?category=shoes
```
## Custom CSRF verifier
Create a new class and extend the ```BaseCsrfVerifier``` middleware class provided with simple-php-router.
Add the property ```except``` with an array of the urls to the routes you would like to exclude from the CSRF validation. Using ```*``` at the end for the url will match the entire url.
Querystrings are ignored.
```php
use Pecee\Http\Middleware\BaseCsrfVerifier;
class CsrfVerifier extends BaseCsrfVerifier {
protected $except = ['/companies/*', '/user/save'];
}
```
Register the new class in your ```routes.php```, custom ```Router``` class or wherever you register your routes.
```php
SimpleRouter::csrfVerifier(new \Demo\Middleware\CsrfVerifier());
```
## Documentation
While I work on a better documentation, please refer to the Laravel 5 routing documentation here:
@@ -239,4 +269,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.
+1 -1
View File
@@ -20,7 +20,7 @@
},
"autoload": {
"psr-4": {
"Pecee\\": "src/"
"Pecee\\": "src/Pecee/"
}
}
}
@@ -0,0 +1,4 @@
<?php
namespace Pecee\Exception;
class TokenMismatchException extends \Exception {}
+40 -6
View File
@@ -1,19 +1,54 @@
<?php
namespace Pecee\Http\Middleware;
use Pecee\CsrfToken;
use Pecee\Exception\TokenMismatchException;
use Pecee\Http\Request;
use Pecee\SimpleRouter\RouterException;
class BaseCsrfVerifier extends Middleware {
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $csrfToken;
public function __construct() {
$this->csrfToken = new CsrfToken();
}
/**
* Check if the url matches the urls in the except property
* @param Request $request
* @return bool
*/
protected function skip(Request $request) {
if($this->except === null || !is_array($this->except)) {
return false;
}
foreach($this->except as $url) {
$url = rtrim($url, '/');
if($url[strlen($url)-1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUri(), $url) === 0);
} else {
$skip = ($url === rtrim($request->getUri(), '/'));
}
if($skip) {
return true;
}
}
return false;
}
public function handle(Request $request) {
if($request->getMethod() != 'get') {
if($request->getMethod() != 'get' && !$this->skip($request)) {
$token = (isset($_POST[self::POST_KEY])) ? $_POST[self::POST_KEY] : null;
@@ -22,9 +57,8 @@ class BaseCsrfVerifier extends Middleware {
$token = $request->getHeader(self::HEADER_KEY);
}
$tokenValidator = new CsrfToken();
if( !$tokenValidator->validate( $token ) ) {
throw new RouterException('Invalid csrf-token.');
if( !$this->csrfToken->validate( $token ) ) {
throw new TokenMismatchException('Invalid csrf-token.');
}
}
+34
View File
@@ -60,6 +60,30 @@ class Request {
return $this->headers;
}
/**
* Get id address
* @return string
*/
public function getIp() {
return isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
}
/**
* Get referer
* @return string
*/
public function getReferer() {
return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
}
/**
* Get user agent
* @return string
*/
public function getUserAgent() {
return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
}
/**
* Get header value by name
* @param string $name
@@ -69,4 +93,14 @@ class Request {
return (isset($this->headers[$name])) ? $this->headers[$name] : null;
}
/**
* Get request input or default value
* @param string $name
* @param string $defaultValue
* @return mixed
*/
public function getInput($name, $defaultValue) {
return (isset($_REQUEST[$name]) ? $_REQUEST[$name] : $defaultValue);
}
}
+52 -3
View File
@@ -21,7 +21,7 @@ class Response {
* @param string $url
*/
public function redirect($url) {
header('location: ' . $url);
$this->header('Location: ' . $url);
die();
}
@@ -29,9 +29,58 @@ class Response {
$this->redirect(url());
}
/**
* Add http authorisation
* @param string $name
* @return self $this
*/
public function auth($name = '') {
header('WWW-Authenticate: Basic realm="' . $name . '"');
header('HTTP/1.0 401 Unauthorized');
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
'HTTP/1.0 401 Unauthorized'
]);
return $this;
}
public function cache($duration = 2592000) {
$this->headers([
'Cache-Control: public,max-age='.$duration.',must-revalidate',
'Expires: '.gmdate('D, d M Y H:i:s',(time()+$duration)).' GMT',
'Last-modified: '.gmdate('D, d M Y H:i:s',time()).' GMT'
]);
return $this;
}
/**
* Json encode array
* @param array $value
*/
public function json(array $value) {
$this->header('Content-type: application/json');
echo json_encode($value);
die();
}
/**
* Add header to response
* @param string $value
* @return self $this
*/
public function header($value) {
header($value);
return $this;
}
/**
* Add multiple headers to response
* @param array $headers
* @return self $this
*/
public function headers(array $headers) {
foreach($headers as $header) {
header($header);
}
return $this;
}
}
+7 -2
View File
@@ -210,7 +210,7 @@ class RouterBase {
protected function processUrl($route, $method = null, $parameters = null, $getParams = null) {
$url = $route->getUrl();
$url = '/' . trim($route->getUrl(), '/');
if(($route instanceof RouterController || $route instanceof RouterResource) && $method !== null) {
$url .= $method;
@@ -230,6 +230,11 @@ class RouterBase {
$url = str_ireplace('{' . $param. '}', $value, $url);
$i++;
}
} else {
// If no parameters are specified in the route, assume that the provided parameters should be used.
if(count($parameters)) {
$url = rtrim($url, '/') . '/' . join('/', $parameters);
}
}
}
@@ -306,7 +311,7 @@ class RouterBase {
ArrayUtil::append($url, $parameters);
}
return join('/', $url);
return '/' . join('/', $url);
}
public static function getInstance() {
+2 -3
View File
@@ -90,8 +90,8 @@ class RouterRoute extends RouterEntry {
}
}
// Add parameter value
$parameters[$parameter] = $parameterValue;
// Add parameter value, if it doesn't exist - replace it with null value
$parameters[$parameter] = ($parameterValue === '') ? null : $parameterValue;
}
}
}
@@ -160,5 +160,4 @@ class RouterRoute extends RouterEntry {
return parent::setSettings($settings);
}
}
+1 -1
View File
@@ -128,7 +128,7 @@ class SimpleRouter {
return $route;
}
public function getRoute($controller = null, $parameters = null, $getParams = null) {
public static function getRoute($controller = null, $parameters = null, $getParams = null) {
return RouterBase::getInstance()->getRoute($controller, $parameters, $getParams);
}