Thay đổi mật khẩu và thông tin tài khoản WordPress từ xa

Lại Đình Cường

Tài liệu thiết kế website

Viết chức năng cho phép thay đổi thông tin tài khoản WordPress trên trang B từ trang A.

Đầu tiên, ở trang WordPress B khai báo đoạn code như sau:

<?php
/**
 * Plugin Name: Intevia Remote User API
 * Description: Secure remote user password updates.
 * Version: 1.0.0
 */

defined('ABSPATH') || exit;

// Store the generated token hash in wp-config.php.
define('INTEVIA_TOKEN_HASH', '$generic$PASTE_YOUR_GENERATED_HASH_HERE');

add_action('rest_api_init', function () {
    register_rest_route('intevia/v1', '/user-password', [
        'methods'             => 'POST',
        'callback'            => 'intevia_remote_update_user_password',
        'permission_callback' => 'intevia_verify_remote_request',
    ]);
});

/**
 * Verify the remote request.
 */
function intevia_verify_remote_request(WP_REST_Request $request) {
    $token     = $request->get_header('x-intevia-token');
    $timestamp = $request->get_header('x-intevia-timestamp');
    $nonce     = $request->get_header('x-intevia-nonce');

    if (
        !defined('INTEVIA_TOKEN_HASH') ||
        empty($token) ||
        empty($timestamp) ||
        empty($nonce)
    ) {
        return new WP_Error(
            'intevia_unauthorized',
            'Unauthorized request.',
            ['status' => 401]
        );
    }

    if (!wp_verify_fast_hash($token, INTEVIA_TOKEN_HASH)) {
        return new WP_Error(
            'intevia_invalid_token',
            'Invalid token.',
            ['status' => 401]
        );
    }

    if (
        !ctype_digit((string) $timestamp) ||
        abs(time() - (int) $timestamp) > 300
    ) {
        return new WP_Error(
            'intevia_expired_request',
            'Request timestamp expired.',
            ['status' => 401]
        );
    }

    if (!preg_match('/^[a-f0-9]{64}$/', $nonce)) {
        return new WP_Error(
            'intevia_invalid_nonce',
            'Invalid nonce.',
            ['status' => 400]
        );
    }

    // Prevent replaying the same request.
    $nonce_key = 'intevia_nonce_' . hash('sha256', $nonce);

    if (get_transient($nonce_key)) {
        return new WP_Error(
            'intevia_replayed_request',
            'Request has already been used.',
            ['status' => 409]
        );
    }

    set_transient($nonce_key, 1, 10 * MINUTE_IN_SECONDS);

    return true;
}

/**
 * Update a user's password.
 */
function intevia_remote_update_user_password(WP_REST_Request $request) {
    $user_id  = absint($request->get_param('user_id'));
    $password = $request->get_param('user_pass');

    if (!$user_id || !is_string($password) || $password === '') {
        return new WP_Error(
            'intevia_invalid_data',
            'Missing or invalid user_id or user_pass.',
            ['status' => 400]
        );
    }

    if (strlen($password) < 12 || strlen($password) > 4096) {
        return new WP_Error(
            'intevia_weak_password',
            'Password must be at least 12 characters and no more than 4096 bytes.',
            ['status' => 400]
        );
    }

    $user = get_userdata($user_id);

    if (!$user) {
        return new WP_Error(
            'intevia_user_not_found',
            'User not found.',
            ['status' => 404]
        );
    }

    // Update the password.
    wp_set_password($password, $user_id);

    // Revoke all existing login sessions for this user.
    WP_Session_Tokens::get_instance($user_id)->destroy_all();

    return new WP_REST_Response([
        'success' => true,
        'message' => 'User password updated successfully.',
        'user_id' => $user_id,
    ], 200);
}

Bây giờ, từ trang A bạn có thể dùng đoạn code bên dưới để đổi thông tin tài khoản cho trang WordPress B:

/**
 * Send a remote WordPress user password update request.
 */
function intevia_send_user_password($site_url, $user_id, $password, $token) {
    if (!function_exists('curl_init')) {
        return [
            'success' => false,
            'message' => 'PHP cURL extension is not enabled.',
        ];
    }

    $endpoint = trailingslashit($site_url) . 'wp-json/intevia/v1/user-password';

    $timestamp = (string) time();
    $nonce     = bin2hex(random_bytes(32));

    $payload = wp_json_encode([
        'user_id'   => absint($user_id),
        'user_pass' => $password,
    ]);

    $ch = curl_init($endpoint);

    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Accept: application/json',
            'X-Intevia-Token: ' . $token,
            'X-Intevia-Timestamp: ' . $timestamp,
            'X-Intevia-Nonce: ' . $nonce,
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_FOLLOWLOCATION => false,
    ]);

    $response  = curl_exec($ch);
    $http_code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);

    curl_close($ch);

    if ($response === false) {
        return [
            'success' => false,
            'message' => 'Connection failed: ' . $curl_error,
            'http_code' => $http_code,
        ];
    }

    $data = json_decode($response, true);

    return [
        'success'   => ($http_code === 200 && !empty($data['success'])),
        'http_code' => $http_code,
        'data'      => $data,
        'message'   => $data['message'] ?? $data['message'] ?? 'Unknown response.',
    ];
}
0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất