Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - How to update user password using REST API

I am using wordpress as well woocommerce for my web store and also using woocommerce REST API for Android app.

I have used WP REST API and JWT Authentication for WP-API plugins for user authentication and login through rest api.

Now when I am using below api to change password

https://www.my-domain.com/wp-json/wp/v2/users/<id>

getting below error

{ "code": "rest_cannot_edit", "message": "Sorry, you are not allowed to edit this user.", "data": { "status": 401 } }

I don't know why am getting this error as authentication is done once at time of login. Can any one please help me?

like image 672
DD77 Avatar asked Mar 24 '17 08:03

DD77


3 Answers

Create your custom api

URL

https://yourdomain/api/change_password.php

Parameter

user_id:10
password:123456  //current password 
new_password:123456

Create folder api in root and create file change_password.php

change_password.php

<?php
include '../wp-load.php';

$user_id = $_REQUEST['user_id'];
$user = get_user_by( 'id', $user_id );

$password = $_REQUEST['password'];
$new_password = $_REQUEST['new_password'];

if(empty($user_id)){
    $json = array('code'=>'0','msg'=>'Please enter user id');
    echo json_encode($json);
    exit;    
}
if(empty($password)){
    $json = array('code'=>'0','msg'=>'Please enter old password');
    echo json_encode($json);
    exit;    
}
if(empty($new_password)){
    $json = array('code'=>'0','msg'=>'Please enter new password');
    echo json_encode($json);
    exit;    
}
$hash = $user->data->user_pass;
$code = 500; $status = false;
if (wp_check_password( $password, $hash ) ){
    $msg = 'Password updated successfully';
    $code = 200; $status = true;
    wp_set_password($new_password , $user_id);
}else{
    $msg = 'Current password does not match.';
}




$json = array('code'=>$code,'status'=>$status,'msg'=>$msg);
echo json_encode($json);
exit;

?>

its working 100% for me try it

like image 125
manoj patel Avatar answered Oct 22 '22 10:10

manoj patel


I had a similar problem. If you have performed all the steps mentioned on the plugin's documentation page, then there might be a problem with the account you're using to get the token.

Below is a video I created which details the whole installation / setup process for the plugin. Try following the steps I outlined and test again.

https://youtu.be/Mp7T7x1oxDk

like image 33
Adrian Oprea Avatar answered Oct 22 '22 08:10

Adrian Oprea


Try to edit your .htaccess file by adding the following lines

RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

and your wp-config.php by adding

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');

do not forget to pass your JWT_token in header API call, like

*Authorization : 'Bearer ' + YOUR_JWT_TOKEN*
like image 1
Mahmoud Avatar answered Oct 22 '22 08:10

Mahmoud