Skip to content

Commit

Permalink
Merge pull request #318 from skipperbent/v3-development
Browse files Browse the repository at this point in the history
Version 3.4.6.0
  • Loading branch information
skipperbent committed Nov 26, 2017
2 parents 496d3e7 + c90c74b commit afc81d7
Show file tree
Hide file tree
Showing 16 changed files with 237 additions and 141 deletions.
132 changes: 106 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,31 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a

The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.

### Ideas and issues
### Feedback and development

If you want a great new feature or experience any issues what-so-ever, please feel free to leave an issue and i'll look into it whenever possible.
If you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.

###### Issues guidelines

- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue.
For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.

- We love to hear out any ideas or feedback to the library.

[Create a new issue here](https://github.com/skipperbent/simple-php-router/issues/new)

###### Contribution development guidelines

- Please try to follow the PSR-2 codestyle guidelines.

- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.

- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.

- When changing existing functionality, please ensure that the unit-tests working.

- When adding new stuff, please remember to add new unit-tests for the functionality.

---

Expand Down Expand Up @@ -51,6 +73,8 @@ If you want a great new feature or experience any issues what-so-ever, please fe
- [CSRF-protection](#csrf-protection)
- [Adding CSRF-verifier](#adding-csrf-verifier)
- [Getting CSRF-token](#getting-csrf-token)
- [Custom CSRF-verifier](#custom-csrf-verifier)
- [Custom Token-provider](#custom-token-provider)

- [Middlewares](#middlewares)
- [Example](#example)
Expand Down Expand Up @@ -215,17 +239,17 @@ Simply create a new `web.config` file in your projects `public` directory and pa
#### Troubleshooting

If you do not have a `favicon.ico` file in your project, you can get a `NotFoundHttpException` (404 - not found).
To add `favicon.ico` to the IIS ignore-list, add the following line to the `<conditions>` group:
To add `favicon.ico` to the IIS ignore-list, add the following line to the `<conditions>` group:
```
<add input="{REQUEST_FILENAME}" negate="true" pattern="favicon.ico" ignoreCase="true" />
```

You can also make one exception for files with some extensions:
You can also make one exception for files with some extensions:
```
<add input="{REQUEST_FILENAME}" pattern="\.ico|\.png|\.css|\.jpg" negate="true" ignoreCase="true" />
```

If you are using `$_SERVER['ORIG_PATH_INFO']`, you will get `\index.php\` as part of the returned value. For example:
If you are using `$_SERVER['ORIG_PATH_INFO']`, you will get `\index.php\` as part of the returned value. For example:
```
/index.php/test/mypage.php
```
Expand Down Expand Up @@ -687,31 +711,16 @@ SimpleRouter::get('/page/404', 'ControllerPage@notFound', ['as' => 'page.notfoun

# CSRF Protection

Any forms posting to `POST`, `PUT` or `DELETE` routes should include the CSRF-token. We strongly recommend that you create your enable CSRF-verification on your site.

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/whitelist from the CSRF validation. Using ```*``` at the end for the url will match the entire url.

**Here's a basic example on a CSRF-verifier class:**
Any forms posting to `POST`, `PUT` or `DELETE` routes should include the CSRF-token. We strongly recommend that you enable CSRF-verification on your site to maximize security.

```php
namespace Demo\Middlewares;

use Pecee\Http\Middleware\BaseCsrfVerifier;
You can use the `BaseCsrfVerifier` to enable CSRF-validation on all request. If you need to disable verification for specific urls, please refer to the "Custom CSRF-verifier" section below.

class CsrfVerifier extends BaseCsrfVerifier
{
/**
* CSRF validation will be ignored on the following urls.
*/
protected $except = ['/api/*'];
}
```
By default simple-php-router will use the `CookieTokenProvider` class. This provider will store the security-token in a cookie on the clients machine.
If you want to store the token elsewhere, please refer to the "Creating custom Token Provider" section below.

## Adding CSRF-verifier

When you've created your CSRF verifier - you need to tell simple-php-router that it should use it. You can do this by adding the following line in your `routes.php` file:
When you've created your CSRF-verifier you need to tell simple-php-router that it should use it. You can do this by adding the following line in your `routes.php` file:

```php
Router::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
Expand All @@ -727,6 +736,12 @@ You can get the CSRF-token by calling the helper method:
csrf_token();
```

You can also get the token directly:

```php
return Router::router()->getCsrfVerifier()->getTokenProvider()->getToken();
```

The default name/key for the input-field is `csrf_token` and is defined in the `POST_KEY` constant in the `BaseCsrfVerifier` class.
You can change the key by overwriting the constant in your own CSRF-verifier class.

Expand All @@ -741,6 +756,70 @@ The example below will post to the current url with a hidden field "`csrf_token`
</form>
```

## Custom CSRF-verifier

Create a new class and extend the `BaseCsrfVerifier` middleware class provided by default with the simple-php-router library.

Add the property `except` with an array of the urls to the routes you want to exclude/whitelist from the CSRF validation.
Using ```*``` at the end for the url will match the entire url.

**Here's a basic example on a CSRF-verifier class:**

```php
namespace Demo\Middlewares;

use Pecee\Http\Middleware\BaseCsrfVerifier;

class CsrfVerifier extends BaseCsrfVerifier
{
/**
* CSRF validation will be ignored on the following urls.
*/
protected $except = ['/api/*'];
}
```

## Custom Token Provider

By default the `BaseCsrfVerifier` will use the `CookieTokenProvider` to store the token in a cookie on the clients machine.

If you need to store the token elsewhere, you can do that by creating your own class and implementing the `ITokenProvider` class.

```php
class SessionTokenProvider implements ITokenProvider
{

/**
* Refresh existing token
*/
public function refresh()
{
// Implement your own functionality here...
}

/**
* Validate valid CSRF token
*
* @param string $token
* @return bool
*/
public function validate($token)
{
// Implement your own functionality here...
}

}
```

Next you need to set your custom `ITokenProvider` implementation on your `BaseCsrfVerifier` class in your routes file:

```php
$verifier = new \dscuz\Middleware\CsrfVerifier();
$verifier->setTokenProvider(new SessionTokenProvider());

Router::csrfVerifier($verifier);
```

---

# Middlewares
Expand Down Expand Up @@ -1034,6 +1113,7 @@ All object implements the `IInputItem` interface and will always contain these m
- `getValue()` - returns the value of the input.

`InputFile` has the same methods as above along with some other file-specific methods like:
- `getFilename` - get the filename.
- `getTmpName()` - get file temporary name.
- `getSize()` - get file size.
- `move($destination)` - move file to destination.
Expand All @@ -1057,7 +1137,7 @@ $siteId = input('site_id', 2, ['post', 'get']);
## Url rewriting
Sometimes it can be useful to manipulate the route about to be loaded.
simple-php-router allows you to easily change the route about to be executed.
All information about the current route is stored in the ```\Pecee\SimpleRouter\Router``` instance's `loadedRoute` property.
All information about the current route is stored in the `\Pecee\SimpleRouter\Router` instance's `loadedRoute` property.

For easy access you can use the shortcut method `\Pecee\SimpleRouter\SimpleRouter::router()`.

Expand Down
2 changes: 1 addition & 1 deletion helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function csrf_token()
{
$baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) {
return $baseVerifier->getToken();
return $baseVerifier->getTokenProvider()->getToken();
}

return null;
Expand Down
21 changes: 12 additions & 9 deletions src/Pecee/Http/Input/Input.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function __construct(Request $request)
public function parseInputs()
{
/* Parse get requests */
if (count($_GET) > 0) {
if (count($_GET) !== 0) {
$this->get = $this->handleGetPost($_GET);
}

Expand All @@ -46,12 +46,12 @@ public function parseInputs()
parse_str(file_get_contents('php://input'), $postVars);
}

if (count($postVars) > 0) {
if (count($postVars) !== 0) {
$this->post = $this->handleGetPost($postVars);
}

/* Parse get requests */
if (count($_FILES) > 0) {
if (count($_FILES) !== 0) {
$this->file = $this->parseFiles();
}
}
Expand All @@ -69,7 +69,7 @@ public function parseFiles()
continue;
}

$keys = [];
$keys = [$key];

$files = $this->rearrangeFiles($value['name'], $keys, $value);

Expand All @@ -87,6 +87,9 @@ public function parseFiles()
protected function rearrangeFiles(array $values, &$index, $original)
{

$originalIndex = $index[0];
array_shift($index);

$output = [];

$getItem = function ($key, $property = 'name') use ($original, $index) {
Expand All @@ -107,7 +110,7 @@ protected function rearrangeFiles(array $values, &$index, $original)
if (is_array($getItem($key)) === false) {

$file = InputFile::createFromArray([
'index' => $key,
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
'filename' => $getItem($key),
'error' => $getItem($key, 'error'),
'tmp_name' => $getItem($key, 'tmp_name'),
Expand All @@ -128,7 +131,7 @@ protected function rearrangeFiles(array $values, &$index, $original)

$files = $this->rearrangeFiles($value, $index, $original);

if (isset($output[$key])) {
if (isset($output[$key]) === true) {
$output[$key][] = $files;
} else {
$output[$key] = $files;
Expand Down Expand Up @@ -217,15 +220,15 @@ public function getObject($index, $defaultValue = null, $methods = null)

$element = null;

if ($methods === null || in_array('get', $methods)) {
if ($methods === null || in_array('get', $methods, false) === true) {
$element = $this->findGet($index);
}

if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods))) {
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods, false) === true)) {
$element = $this->findPost($index);
}

if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods))) {
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods, false) === true)) {
$element = $this->findFile($index);
}

Expand Down
10 changes: 6 additions & 4 deletions src/Pecee/Http/Input/InputFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public function __construct($index)
$this->index = $index;

// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
$this->name = ucfirst(str_replace('_', ' ', strtolower($this->index)));
}

/**
Expand All @@ -28,7 +28,7 @@ public function __construct($index)
*/
public static function createFromArray(array $values)
{
if (!isset($values['index'])) {
if (isset('index', $values) === false) {
throw new \InvalidArgumentException('Index key is required');
}

Expand All @@ -39,6 +39,7 @@ public static function createFromArray(array $values)
'type' => null,
'size' => null,
'name' => null,
'filename' => null,
'error' => null,
], $values);

Expand All @@ -47,7 +48,7 @@ public static function createFromArray(array $values)
->setError($values['error'])
->setType($values['type'])
->setTmpName($values['tmp_name'])
->setFilename($values['name']);
->setFilename($values['filename']);

}

Expand Down Expand Up @@ -267,8 +268,9 @@ public function toArray()
'tmp_name' => $this->tmpName,
'type' => $this->type,
'size' => $this->size,
'name' => $this->filename,
'name' => $this->name,
'error' => $this->error,
'filename' => $this->filename,
];
}

Expand Down
2 changes: 1 addition & 1 deletion src/Pecee/Http/Input/InputItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function __construct($index, $value = null)
$this->value = $value;

// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
$this->name = ucfirst(str_replace('_', ' ', strtolower($this->index)));
}

/**
Expand Down
Loading

0 comments on commit afc81d7

Please sign in to comment.