Skip to content

Commit

Permalink
Merge pull request #3 from dwnload/develop
Browse files Browse the repository at this point in the history
Add new methods with filters to re-check requests containing `?contex…
  • Loading branch information
thefrosty authored Apr 26, 2018
2 parents a564df7 + 498a769 commit db8597b
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 4 deletions.
8 changes: 8 additions & 0 deletions CHANGELONG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## 1.2.0 - 2018-04-25
### Added
- Added new method `RestDispatch::queryParamContextIsEdit`
- Added new method `RestDispatch::isUserAuthenticated`.

### Updated
- `RestDispatch::isUserAuthenticated` uses a new filter `RestDispatch::FILTER_CACHE_VALIDATE_AUTH` to re-check requests containing `?context=edit` to avoid race conditions where a non-auth request returns results from cache.

## 1.1.1 - 2018-04-23
### Updated
- Version bump for packagist.
Expand Down
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ To install this package, edit your `composer.json` file:
```js
{
"require": {
"dwnload/wp-rest-api-object-cache": "^1.1.1"
"dwnload/wp-rest-api-object-cache": "^1.2.0"
}
}
```
Expand Down Expand Up @@ -71,6 +71,7 @@ Filters
| Dwnload\WpRestApi\WpAdmin\Admin::FILTER_SHOW_ADMIN_MENU | boolean **$show** |
| Dwnload\WpRestApi\WpAdmin\Admin::FILTER_SHOW_ADMIN_BAR_MENU | boolean **$show** |
| Dwnload\WpRestApi\RestApi\RestDispatch::FILTER_ALLOWED_CACHE_STATUS | array **$status** HTTP Header statuses (defaults to `array( 200 )` |
| Dwnload\WpRestApi\RestApi\RestDispatch::FILTER_CACHE_VALIDATE_AUTH | boolean **$authenticated**<br>WP_REST_Request $request |

How to use filters
----
Expand Down Expand Up @@ -110,6 +111,21 @@ add_filter( Admin::FILTER_CACHE_OPTIONS, function( array $options ) : array {
} );
```

**Validating user auth when `?context=edit`**

```php
use Dwnload\WpRestApi\RestApi\RestDispatch;
add_filter( RestDispatch::FILTER_CACHE_VALIDATE_AUTH, function( bool $auth, WP_REST_Request $request ) : bool {
// If you are running the Basic Auth plugin.
if ( $GLOBALS['wp_json_basic_auth_error'] === true ) {
$authorized = true;
}
// Otherwise, maybe do some additional logic on the request for current user...

return $authorized;
}, 10, 2 );
```

**Skipping cache**

```php
Expand Down Expand Up @@ -146,3 +162,13 @@ add_action( 'save_post', function( $post_id ) {
}
} );
```

**Maybe better to use `transition_post_status`**

```php
add_action( 'transition_post_status', function( string $new_status, string $old_status, \WP_Post $post ) {
if ( 'publish' === $new_status || 'publish' === $old_status ) {
\wp_cache_flush();
}
}, 99, 3 );
```
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "dwnload/wp-rest-api-object-cache",
"description": "Enable object caching for WordPress' REST API. Aids in increased response times of your applications endpoints.",
"type": "wordpress-plugin",
"version": "1.1.1",
"version": "1.2.0",
"license": "MIT",
"authors": [
{
Expand Down
44 changes: 43 additions & 1 deletion src/RestApi/RestDispatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class RestDispatch implements WpHooksInterface
const FILTER_API_KEY = WpRestApiCache::FILTER_PREFIX . 'key';
const FILTER_KEYS_NOT_ALLOWED = WpRestApiCache::FILTER_PREFIX . 'keys_not_allowed';
const FILTER_ALLOWED_CACHE_STATUS = WpRestApiCache::FILTER_PREFIX . 'allowed_cache_status';
const FILTER_CACHE_VALIDATE_AUTH = WpRestApiCache::FILTER_PREFIX . 'validate_auth';
const FILTER_CACHE_CONTROL_HEADERS = WpRestApiCache::FILTER_PREFIX . 'cache_control_headers';
const FILTER_CACHE_EXPIRE = WpRestApiCache::FILTER_PREFIX . 'expire';
const FILTER_CACHE_HEADERS = WpRestApiCache::FILTER_PREFIX . 'headers';
Expand All @@ -42,7 +43,7 @@ class RestDispatch implements WpHooksInterface
const QUERY_CACHE_FORCE_DELETE = 'rest_force_delete';
const QUERY_CACHE_REFRESH = 'rest_cache_refresh';

const VERSION = '1.1.0';
const VERSION = '1.2.0';

/**
* Add class hooks.
Expand Down Expand Up @@ -226,6 +227,14 @@ protected function getCachedResult(
return $result;
}

/*
* Attempt to validate the user if `?context=edit` to avoid returning results for non-auth'd requests after
* a cached request from an authenticated request happens before cache flush.
*/
if ($this->queryParamContextIsEdit($request) && ! $this->isUserAuthenticated($request)) {
return $this->dispatchRequest($server, $request);
}

return $result;
}

Expand Down Expand Up @@ -301,4 +310,37 @@ private function validateQueryParam(WP_REST_Request $request, string $key) : boo
return \array_key_exists($key, $request->get_query_params()) &&
filter_var_int($request->get_query_params()[$key]) === 1;
}

/**
* Validate the HTTP query param.
*
* @param WP_REST_Request $request
*
* @return bool
*/
private function queryParamContextIsEdit(WP_REST_Request $request) : bool
{
return (
array_key_exists('context', $request->get_query_params()) &&
$request->get_query_params()['context'] === 'edit'
);
}

/**
* Apply a filter to allow user auth checks based on the $request headers.
* A great example here is to use the Basic Auth plugin and check for the global `$wp_json_basic_auth_error`
* is equal to true to validate the current request is an authenticated user.
*
* @param WP_REST_Request $request
*
* @return bool
*/
private function isUserAuthenticated(WP_REST_Request $request) : bool
{
/**
* @param bool $authenticated Defaults to false, user needs to be authenticated.
* @param WP_REST_Request $request
*/
return \apply_filters(self::FILTER_CACHE_VALIDATE_AUTH, false, $request) !== false;
}
}
2 changes: 1 addition & 1 deletion wp-rest-api-cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Description: Enable object caching for WordPress' REST API. Aids in increased response times of your applications endpoints.
* Author: Austin Passy
* Author URI: http://github.com/thefrosty
* Version: 1.1.1
* Version: 1.2.0
* Requires at least: 4.9
* Tested up to: 4.9
* Requires PHP: 7.0
Expand Down

0 comments on commit db8597b

Please sign in to comment.