refactored API class

This commit is contained in:
Jonathan Labreuille
2016-10-20 16:38:24 +02:00
parent 876d21300a
commit ee89bf0722
9 changed files with 27 additions and 29 deletions

View File

@ -33,7 +33,18 @@ class API {
function setupAjax() {
$this->getRequestData();
$this->checkToken();
if($this->checkToken() === false) {
$error_response = new ErrorResponse(
array(
Error::UNAUTHORIZED => __('Invalid request.', 'mailpoet')
),
array(),
Response::STATUS_UNAUTHORIZED
);
$error_response->send();
}
$this->processRoute();
}
@ -96,23 +107,7 @@ class API {
||
$permissions[$this->_method] !== Access::ALL
) {
$this->checkPermissions();
}
$response = $endpoint->{$this->_method}($this->_data);
$response->send();
} catch(\Exception $e) {
$error_response = new ErrorResponse(
array($e->getCode() => $e->getMessage())
);
$error_response->send();
}
}
function checkPermissions() {
$has_permission = current_user_can('manage_options');
if($has_permission === false) {
if($this->checkPermissions() === false) {
$error_response = new ErrorResponse(
array(
Error::FORBIDDEN => __(
@ -127,21 +122,24 @@ class API {
}
}
function checkToken() {
$is_valid_token = wp_verify_nonce($this->_token, 'mailpoet_token');
if($is_valid_token === false) {
$response = $endpoint->{$this->_method}($this->_data);
$response->send();
} catch(\Exception $e) {
$error_response = new ErrorResponse(
array(
Error::UNAUTHORIZED => __('Invalid request.', 'mailpoet')
),
array(),
Response::STATUS_UNAUTHORIZED
array($e->getCode() => $e->getMessage())
);
$error_response->send();
}
}
function checkPermissions() {
return current_user_can('manage_options');
}
function checkToken() {
return wp_verify_nonce($this->_token, 'mailpoet_token');
}
function setToken() {
$global = '<script type="text/javascript">';
$global .= 'var mailpoet_token = "';