PluginProbe
NETSENSAI Shield / trunk
NETSENSAI Shield vtrunk
1.6.1 trunk 1.1 1.2 1.3 1.4 1.4.1 1.4.2 1.4.3 1.4.5 1.4.6 1.4.7 1.4.8 1.4.9 1.6.0
netsensai-shield / includes / disable_wp_api_json.php

disable_wp_api_json.php in NETSENSAI Shield trunk, at includes/disable_wp_api_json.php

41 lines 1.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 // Exit if accessed directly.
3 if ( ! defined( 'ABSPATH' ) ) {
4 exit;
5 }
6
7 /**
8 * Disable WP API JSON for unauthenticated users except for allowed paths.
9 *
10 * This function retrieves the setting for "Disable WP API JSON" and, if enabled and the user is not logged in,
11 * adds a filter to the REST API authentication errors. The filter checks the REQUEST_URI and allows access if
12 * it matches one of the specified allowed paths. Otherwise, it returns a 401 error.
13 *
14 * @return void
15 */
16 function ns_shield_disable_wp_api_json() {
17 // Get the setting for disabling WP API JSON.
18 $is_api_json_disabled = get_option( 'ns_shield_wp_api_json', false );
19
20 if ( $is_api_json_disabled && ! is_user_logged_in() ) {
21 add_filter( 'rest_authentication_errors', function( $result ) {
22 // Define allowed paths.
23 $allowed_paths = array( '/wp-json/edd/', '/platnosc/' );
24
25 // Safely retrieve and sanitize the REQUEST_URI.
26 $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
27
28 // Check if the REQUEST_URI contains any allowed path.
29 foreach ( $allowed_paths as $path ) {
30 if ( strpos( $request_uri, $path ) !== false ) {
31 return $result; // Allow access for allowed paths.
32 }
33 }
34
35 // Return an error if the user is not logged in and the requested path is not allowed.
36 return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
37 } );
38 }
39 }
40 add_action( 'rest_api_init', 'ns_shield_disable_wp_api_json' );
41