<?php

/**
 * Plugin Name: WP REST API Basic Authentication
 * Plugin URI: https://codewp.ai
 * Description: This WordPress plugin requires users to have basic authentication to access the WP REST API if they're not logged in.
 * Version: 1.0
 * Author: CodeWP Assistant
 * Author URI: https://codewp.ai
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    die;
}

// Add a hook before the REST API is initialized
add_action('rest_api_init', 'codewp_check_rest_authentication', 0);

function codewp_check_rest_authentication() {
    // If the user is already logged in, let them access the API
    if (is_user_logged_in()) {
        return;
    }

    // If not, check if they have supplied basic authentication headers
    $user = codewp_check_basic_auth();
    if (!$user) {
        // If not, block access and send a 401 Unauthorized status
        wp_send_json_error('You must be logged in or supply valid basic auth credentials to access the REST API.', 401);
    }
}

function codewp_check_basic_auth() {
    // Check if the PHP_AUTH_USER and PHP_AUTH_PW server variables have been set
    if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
        return false;
    }

    // Try to log in the user with the supplied username and password
    $user = wp_authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);

    // If the login failed, return false
    if (is_wp_error($user)) {
        return false;
    }

    // If the login was successful, return the user
    return $user;
}