refactor API error handling and response structure
All checks were successful
Deploy Workshop-Wahlen (DEV / PROD) / deploy (push) Successful in 12s
All checks were successful
Deploy Workshop-Wahlen (DEV / PROD) / deploy (push) Successful in 12s
This commit is contained in:
@@ -4,17 +4,17 @@ if (!defined('ABSPATH')) exit;
|
|||||||
function kc_api_permission_check() {
|
function kc_api_permission_check() {
|
||||||
if (!is_user_logged_in()) {
|
if (!is_user_logged_in()) {
|
||||||
return new WP_Error(
|
return new WP_Error(
|
||||||
'kc_api_auth_required',
|
'rest_no_route',
|
||||||
'Authentifizierung erforderlich.',
|
'Es wurde keine Route gefunden, die mit der URL und der Request-Methode identisch ist.',
|
||||||
['status' => 401]
|
['status' => 404]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!current_user_can('manage_options')) {
|
if (!current_user_can('manage_options')) {
|
||||||
return new WP_Error(
|
return new WP_Error(
|
||||||
'kc_api_forbidden',
|
'rest_no_route',
|
||||||
'Keine Berechtigung für diese API.',
|
'Es wurde keine Route gefunden, die mit der URL und der Request-Methode identisch ist.',
|
||||||
['status' => 403]
|
['status' => 404]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,16 +118,34 @@ add_action('rest_api_init', function() {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
add_filter('rest_endpoints', function($endpoints) {
|
add_filter('rest_index', function($response) {
|
||||||
if (current_user_can('manage_options')) {
|
if (current_user_can('manage_options')) {
|
||||||
return $endpoints;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($endpoints as $route => $handlers) {
|
if (!($response instanceof WP_REST_Response)) {
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = $response->get_data();
|
||||||
|
if (!is_array($data)) {
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($data['namespaces']) && is_array($data['namespaces'])) {
|
||||||
|
$data['namespaces'] = array_values(array_filter($data['namespaces'], function($ns) {
|
||||||
|
return $ns !== 'kc-internal/v1';
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($data['routes']) && is_array($data['routes'])) {
|
||||||
|
foreach ($data['routes'] as $route => $route_config) {
|
||||||
if (strpos($route, '/kc-internal/v1/') === 0) {
|
if (strpos($route, '/kc-internal/v1/') === 0) {
|
||||||
unset($endpoints[$route]);
|
unset($data['routes'][$route]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $endpoints;
|
$response->set_data($data);
|
||||||
|
return $response;
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user