enhance API authentication and error handling
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() {
|
||||
if (!is_user_logged_in()) {
|
||||
return new WP_Error(
|
||||
'rest_no_route',
|
||||
'Es wurde keine Route gefunden, die mit der URL und der Request-Methode identisch ist.',
|
||||
['status' => 404]
|
||||
'kc_api_auth_required',
|
||||
'Authentifizierung erforderlich.',
|
||||
['status' => 401]
|
||||
);
|
||||
}
|
||||
|
||||
if (!current_user_can('manage_options')) {
|
||||
return new WP_Error(
|
||||
'rest_no_route',
|
||||
'Es wurde keine Route gefunden, die mit der URL und der Request-Methode identisch ist.',
|
||||
['status' => 404]
|
||||
'kc_api_forbidden',
|
||||
'Keine Berechtigung für diese API.',
|
||||
['status' => 403]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -97,7 +97,28 @@ function kc_api_get_wahl_zuteilungen(WP_REST_Request $request) {
|
||||
]);
|
||||
}
|
||||
|
||||
function kc_api_get_status(WP_REST_Request $request) {
|
||||
$user = wp_get_current_user();
|
||||
|
||||
return rest_ensure_response([
|
||||
'success' => true,
|
||||
'authenticated' => is_user_logged_in(),
|
||||
'authorized' => current_user_can('manage_options'),
|
||||
'user' => [
|
||||
'id' => intval($user->ID),
|
||||
'login' => (string) $user->user_login,
|
||||
'display_name' => (string) $user->display_name,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
add_action('rest_api_init', function() {
|
||||
register_rest_route('kc-internal/v1', '/status', [
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => 'kc_api_get_status',
|
||||
'permission_callback' => 'kc_api_permission_check',
|
||||
]);
|
||||
|
||||
register_rest_route('kc-internal/v1', '/wahlen', [
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => 'kc_api_get_wahlen',
|
||||
@@ -149,3 +170,21 @@ add_filter('rest_index', function($response) {
|
||||
$response->set_data($data);
|
||||
return $response;
|
||||
});
|
||||
|
||||
add_filter('rest_post_dispatch', function($response, $server, $request) {
|
||||
if (!($response instanceof WP_REST_Response) || !($request instanceof WP_REST_Request)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$route = $request->get_route();
|
||||
if (strpos($route, '/kc-internal/v1/') !== 0) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
if (intval($response->get_status()) === 401) {
|
||||
$response->header('WWW-Authenticate', 'Basic realm="KC Internal API"');
|
||||
$response->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
return $response;
|
||||
}, 10, 3);
|
||||
|
||||
Reference in New Issue
Block a user