Add unit tests for API endpoints injection [PREMIUM-4]

This commit is contained in:
Alexey Stoletniy
2017-02-22 18:02:58 +03:00
parent 6c7cc5de0d
commit bb80fc0860
3 changed files with 92 additions and 14 deletions

View File

@ -1,5 +1,7 @@
<?php
namespace MailPoet\API;
use MailPoet\Util\Helpers;
use MailPoet\Util\Security;
if(!defined('ABSPATH')) exit;
@ -40,7 +42,7 @@ class API {
function setupAjax() {
do_action('mailpoet_api_setup', array($this));
$this->getRequestData();
$this->getRequestData($_POST);
if($this->checkToken() === false) {
$error_response = new ErrorResponse(
@ -53,18 +55,19 @@ class API {
$error_response->send();
}
$this->processRoute();
$response = $this->processRoute();
$response->send();
}
function getRequestData() {
$this->_endpoint = isset($_POST['endpoint'])
? trim($_POST['endpoint'])
function getRequestData($data) {
$this->_endpoint = isset($data['endpoint'])
? Helpers::underscoreToCamelCase(trim($data['endpoint']))
: null;
$this->_method = isset($_POST['method'])
? trim($_POST['method'])
$this->_method = isset($data['method'])
? Helpers::underscoreToCamelCase(trim($data['method']))
: null;
$this->_token = isset($_POST['token'])
? trim($_POST['token'])
$this->_token = isset($data['token'])
? trim($data['token'])
: null;
if(!$this->_endpoint || !$this->_method) {
@ -85,8 +88,8 @@ class API {
}
}
$this->_data = isset($_POST['data'])
? stripslashes_deep($_POST['data'])
$this->_data = isset($data['data'])
? stripslashes_deep($data['data'])
: array();
// remove reserved keywords from data
@ -108,6 +111,10 @@ class API {
function processRoute() {
try {
if(empty($this->_endpoint_class)) {
throw new \Exception('Invalid endpoint');
}
$endpoint = new $this->_endpoint_class();
// check the accessibility of the requested endpoint's action
@ -129,17 +136,17 @@ class API {
array(),
Response::STATUS_FORBIDDEN
);
$error_response->send();
return $error_response;
}
}
$response = $endpoint->{$this->_method}($this->_data);
$response->send();
return $response;
} catch(\Exception $e) {
$error_response = new ErrorResponse(
array($e->getCode() => $e->getMessage())
);
$error_response->send();
return $error_response;
}
}
@ -163,4 +170,8 @@ class API {
function addEndpointNamespace($namespace) {
$this->_endpoint_namespaces[] = $namespace;
}
function getEndpointNamespaces() {
return $this->_endpoint_namespaces;
}
}