programing

WordPress REST API를 사용한AJAX 경유 비밀번호 변경

megabox 2023. 2. 23. 22:41
반응형

WordPress REST API를 사용한AJAX 경유 비밀번호 변경

WordPress REST API를 사용하여 비밀번호 변경 양식을 작성하고 있습니다.사용자가 새로운 비밀번호를 입력하면 AJAX 경유로 커스텀엔드포인트에 송신됩니다.이 비밀번호는 다음과 같습니다.

$userID = get_current_user_id();
wp_set_password($password, $userID);

//Log user in and update auth cookie
wp_set_current_user($userID);
wp_set_auth_cookie($userID);
//Set the cookie immediately
$_COOKIE[AUTH_COOKIE] = wp_generate_auth_cookie($userID, 2 * DAY_IN_SECONDS);

//Return fresh nonce
return new WP_Rest_Response(array(
    'nonce' => wp_create_nonce('wp_rest')
));

엔드포인트는 사용자가 새 비밀번호로 다시 로그인할 필요가 없도록 자동으로 로그인하고 새 난스를 반환해야 합니다.

문제는 반환된 난스가 완전히 동일하고 유효하지 않다는 것입니다.페이지를 새로 고쳐야 새 난스를 얻을 수 있습니다.어떤 것 같다$_COOKIE또는$_SESSIONWordPress가 난스를 생성하는 데 사용하는 변수는 페이지가 새로 고쳐질 때까지 업데이트되지 않습니다.

도와주셔서 고마워요.

약간의 $_COOK가 있는 것 같습니다.WordPress가 난스를 생성하는 데 사용하는 IE 또는 $_SESSION 변수는 페이지를 새로 고칠 때까지 업데이트되지 않습니다.

네, 디폴트는 다음과 같습니다.

'wordpress_logged_in_' . COOKIEHASH

다음 항목을 참조하십시오.

그래서 이 코드를 대체해 주세요: (그리고 저는wp_generate_auth_cookie()이 목적을 위해서, 대신에, 이미 생성된 것을 사용해 주세요.wp_set_auth_cookie())

//Set the cookie immediately
$_COOKIE[AUTH_COOKIE] = wp_generate_auth_cookie($userID, 2 * DAY_IN_SECONDS);

..이걸로:

$_set_cookies = true; // for the closures

// Set the (secure) auth cookie immediately. We need only the first and last
// arguments; hence I renamed the other three, namely `$a`, `$b`, and `$c`.
add_action( 'set_auth_cookie', function( $auth_cookie, $a, $b, $c, $scheme ) use( $_set_cookies ){
    if ( $_set_cookies ) {
        $_COOKIE[ 'secure_auth' === $scheme ? SECURE_AUTH_COOKIE : AUTH_COOKIE ] = $auth_cookie;
    }
}, 10, 5 );

// Set the logged-in cookie immediately. `wp_create_nonce()` relies upon this
// cookie; hence, we must also set it.
add_action( 'set_logged_in_cookie', function( $logged_in_cookie ) use( $_set_cookies ){
    if ( $_set_cookies ) {
        $_COOKIE[ LOGGED_IN_COOKIE ] = $logged_in_cookie;
    }
} );

// Set cookies.
wp_set_auth_cookie($userID);
$_set_cookies = false;

작업 예(WordPress 4.9.5에서 테스트됨)

PHP/WP REST API

function myplugin__change_password( $password, $userID ) {
    //$userID = get_current_user_id();
    wp_set_password($password, $userID);

    // Log user in.
    wp_set_current_user($userID);
    $_set_cookies = true; // for the closures

    // Set the (secure) auth cookie immediately. We need only the first and last
    // arguments; hence I renamed the other three, namely `$a`, `$b`, and `$c`.
    add_action( 'set_auth_cookie', function( $auth_cookie, $a, $b, $c, $scheme ) use( $_set_cookies ){
        if ( $_set_cookies ) {
            $_COOKIE[ 'secure_auth' === $scheme ? SECURE_AUTH_COOKIE : AUTH_COOKIE ] = $auth_cookie;
        }
    }, 10, 5 );

    // Set the logged-in cookie immediately. `wp_create_nonce()` relies upon this
    // cookie; hence, we must also set it.
    add_action( 'set_logged_in_cookie', function( $logged_in_cookie ) use( $_set_cookies ){
        if ( $_set_cookies ) {
            $_COOKIE[ LOGGED_IN_COOKIE ] = $logged_in_cookie;
        }
    } );

    // Set cookies.
    wp_set_auth_cookie($userID);
    $_set_cookies = false;

    //Return fresh nonce
    return new WP_Rest_Response(array(
        'nonce'  => wp_create_nonce('wp_rest'),
        'status' => 'password_changed',
    ));
}

function myplugin_change_password( WP_REST_Request $request ) {
    $old_pwd = $request->get_param( 'old_pwd' );
    $new_pwd = $request->get_param( 'new_pwd' );

    $user = wp_get_current_user();
    if ( ! wp_check_password( $old_pwd, $user->user_pass, $user->ID ) ) {
        return new WP_Error( 'wrong_password', 'Old password incorrect' );
    }

    if ( $old_pwd !== $new_pwd ) {
        return myplugin__change_password( $new_pwd, $user->ID );
    }

    return new WP_Rest_Response( [
        'nonce'  => wp_create_nonce( 'wp_rest' ),
        'status' => 'passwords_equal',
    ], 200 );
}

add_action( 'rest_api_init', function(){
    register_rest_route( 'myplugin/v1', '/change-password', [
        'methods'             => 'POST',
        'callback'            => 'myplugin_change_password',
        'args'                => [
            'old_pwd' => [
                'type'              => 'string',
                'validate_callback' => function( $param ) {
                    return ! empty( $param );
                }
            ],
            'new_pwd' => [
                'type'              => 'string',
                'validate_callback' => function( $param ) {
                    return ! empty( $param );
                }
            ],
        ],
        'permission_callback' => function(){
            // Only logged-in users.
            return current_user_can( 'read' );
        },
    ] );
} );

HTML / 폼

<fieldset>
    <legend>Change Password</legend>

    <p>
        To change your password, please enter your old or current password.
    </p>

    <label>
        Old Password:
        <input id="old_passwd">
    </label>
    <label>
        New Password:
        <input id="new_passwd">
    </label>

    <label>
        Old nonce: (read-only)
        <input id="old_nonce" value="<?= wp_create_nonce( 'wp_rest' ) ?>"
        readonly disabled>
    </label>
    <label>
        New nonce: (read-only)
        <input id="new_nonce" readonly disabled>
    </label>

    <button id="go" onclick="change_passwd()">Change</button>
</fieldset>
<div id="rest-res"><!-- AJAX response goes here --></div>

jQuery / AJAX

function change_passwd() {
    var apiurl = '/wp-json/myplugin/v1/change-password',
        $ = jQuery;

    $.post( apiurl, {
        old_pwd: $( '#old_passwd' ).val(),
        new_pwd: $( '#new_passwd' ).val(),
        _wpnonce: $( '#new_nonce' ).val() || $( '#old_nonce' ).val()
    }, function( res ){
        $( '#new_nonce' ).val( res.nonce );

        // Update the global nonce for scripts using the `wp-api` script.
        if ( 'object' === typeof wpApiSettings ) {
            wpApiSettings.nonce = res.nonce;
        }

        $( '#rest-res' ).html( '<b>Password changed successfully.</b>' );
    }, 'json' ).fail( function( xhr ){
        try {
            var res = JSON.parse( xhr.responseText );
        } catch ( err ) {
            return;
        }

        if ( res.code ) {
            $( '#rest-res' ).html( '<b>[ERROR]</b> ' + res.message );
        }
    });
}

난스를 통과시켜야 합니다.X-WP-Nonceheader에 AJAX 요청을 입력합니다.예를 들어 다음과 같습니다.

beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', localizedScript.nonce );
}

어디에localizedScript는 난스가 현지화되어 있는 스크립트입니다.현지화의 상세한 것에 대하여는, 코덱스를 참조해 주세요.주의:localizedScript메서드는 필요하지 않습니다.

미포함localizedSriptAJAX는 다음과 같이 표시될 수 있습니다.

var _nonce = "<?php echo wp_create_nonce( 'wp_rest' ); ?>";
$.ajax({
    type: 'POST',
    url: url_path,
    data: {},
    dataType: 'json',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', _nonce );
    }
});

의 스크립트를 그대로 복사하는 것으로는 충분치 않지만 난스를 성공적으로 통과하려면 기본적으로 그렇게 해야 합니다.

언급URL : https://stackoverflow.com/questions/45416421/changing-password-via-ajax-with-the-wordpress-rest-api

반응형