how to login user throught rest api in wordpress - wordpress

hey i just creat a rest api in wordpress for login its work on old user but when i creat a new user its show invalid user name 400 error
my code is its work on old user but error in new user like this
{"code":400,"msg":"Invalid username"}
and in register api how to convert user password to wordpress hash password
add_action( 'rest_api_init', 'register_api_hooks' );
function register_api_hooks() {
register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'GET',
'callback' => 'login',
)
);
}
function login($request){
$creds = array();
$creds['user_login'] = $request["username"];
$creds['user_password'] = md5($request["password"]);
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
{
$user->get_error_message();
return $myArray = ['code'=>400, 'msg'=>'Invalid username'];
}
else
{
$token = wp_get_session_token();
return $myArray = ['code'=>200, 'msg'=>'Success', 'user'=> $user ,'token'=> $token];
}
}
add_action( 'after_setup_theme', 'custom_login' );

Related

Woocommerce REST API add_filter not working

I have created an API to add new cart item data using API. I think filter is not working in code.
Registered Route :
register_rest_route(
'ecm-api', '/setGiftMessage/',
array(
'methods' => 'POST',
'callback' => array($this,'setGiftMessage')
)
);
defination of function:
public function setGiftMessage($request){
global $woocommerce,$sitepress;
$woocommerce->frontend_includes();
$lang = $request['lang'];
$user_id = $request['user_id'];
$product_id = $request['product_id'];
$written_message = $request['written_message'];
if(empty($user_id)){
$response['status'] = 0;
$response['message'] = __('User id is required', self::domainText);
$response['data'] = new stdClass();
return new WP_REST_Response($response, 200);
}
wp_set_current_user( $user_id );
$woocommerce->session = new WC_Session_Handler();
$woocommerce->session->init();
$woocommerce->customer = new WC_Customer( get_current_user_id(), true );
$woocommerce->cart = new WC_Cart();
$items = $woocommerce->cart->get_cart();
add_filter( 'woocommerce_add_cart_item_data',function($cart_item_data, $product_id, $variation_id) use($request) {
$cart_item_data['msg_on_gift']='wish you happy birthday';
return $cart_item_data;
}, 10, 3 );
$woocommerce->cart->persistent_cart_update();
$response['status'] = $cart_item_data;
$response['message'] = __("Gift Message to saved", self::domainText);
return new WP_REST_Response($response, 200);
}
I also tried to register the filter as a separated function:
add_filter('woocommerce_add_cart_item_data',array($this,'add_gift_message_to_cart'),10, 3 );
public function add_gift_message_to_cart($cart_item_data, $product_id, $variation_id)
{
$cart_item_data['msg_on_gift']='wish you happy birthday';
return $cart_item_data;
}

Login WP - Connect single field to an external api

I made a plugin to allow wordpress login with external api.
Everything works, now what I have to do is that when a user logs in for the first time, the plugin checks to see if it is already present on wp, and where it was not already present, it creates a new user by taking behind username, email and password.
The new user is created but I would like it to bring with it also the id field from the external api saving it in an ACF field.
This is the code created so far:
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
$user_email_key = 'email';
$password_key = 'password';
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
// Check user exists locally
$user_exists = wp_authenticate_username_password(null, $username, $password);
if ($user_exists && $user_exists instanceof WP_User) {
$user = new WP_User($user_exists);
return $user;
}
// Build the POST request
$login_data = array(
$user_email_key => $username,
$password_key => $password
);
$auth_args = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'sslverify' => false,
'body' => $login_data
);
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$response_code = $response['response']['code'];
if ($response_code == 400) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __("<strong>Error</strong>: Your username or password are incorrect."));
} else if ($response_code == 200) {
// External user exists, try to load the user info from the WordPress user table
$userobj = new WP_User();
// Does not return a WP_User object but a raw user object
$user = $userobj->get_data_by('email', $username);
if ($user && $user->ID) {
// Attempt to load the user with that ID
$user = new WP_User($user->ID);
}
} else {
// The user does not currently exist in the WordPress user table.
// Setup the minimum required user information
$userdata = array(
'user_email' => $username,
'user_login' => $username,
'user_pass' => $password
);
// A new user has been created
$new_user_id = wp_insert_user($userdata);
// Assign editor role to the new user (so he can access protected articles)
wp_update_user(
array(
'ID' => $new_user_id,
'role' => 'editor'
)
);
// Load the new user info
$user = new WP_User ($new_user_id);
}
}
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}
Anyone have any way how to help me?
Resolved! I hope this will help those who have found themselves in the same situation as me:
add_filter('authenticate', 'au_auth', 10, 3);
add_filter('register_new_user', 'au_registration', 10, 3);
// add_filter('profile_update', 'au_profile_update', 10, 3);
// add_filter('edit_user_profile_update', 'au_profile_edit', 10, 3);
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
$auth_args = [
'method' => 'POST',
'headers' => [
'Content-type: application/x-www-form-urlencoded',
],
'sslverify' => false,
'body' => [
'email' => $username,
'password' => $password,
],
];
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$body = json_decode($response['body'], true);
$response_status_code = $response['response']['code'];
$success = $body !== 'KO';
if (!$success) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __('<strong>Error</strong>: Your username
or password are incorrect.'));
} elseif ($success) {
$idExternal = $body['Id'];
$nome = $body['Name'];
$cognome = $body['Surname'];
$email = $body['Email'];
$userobj = new WP_User();
$user = $userobj->get_data_by('email', $email);
if ($user && $user->ID) {
$user = new WP_User($user->ID);
} else {
$userdata = [
'user_email' => $email,
'user_login' => join(' ', [$name, $surname]),
'user_pass' => '----',
];
$new_user_id = wp_insert_user($userdata);
$new_user_composite_id = 'user_' . $new_user_id;
update_field('field_60084ad3970a8', $idExternal, $new_user_composite_id);
update_field('field_5f22ca201c7b0', $name, $new_user_composite_id);
update_field('field_5f22ccd498f40', $surname, $new_user_composite_id);
update_field('field_5f22ce7b7c1db', $email, $new_user_composite_id);
$user = new WP_User($new_user_id);
}
}
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}

auto-responder with login details in Symfony

Here is the funcion im using
public function sendCredentialsEmailMessage(UserInterface $user)
{
$template = 'Emails/afterRegister.html.twig';
$rendered = $this->templating->render($template, array(
'user' => $user,
));
$this->sendEmailMessage($rendered,
$this->parameters['from_email']['confirmation'], $user->getEmail());
}
Basically I want the auto-mailer to send my template along with the login name. When i create a new user nothing is being sent. My email template is located in app>resources>views>emails>
and this controller file is located in src>myname>userbundle>mailer>
protected function sendEmailMessage($renderedTemplate, $fromEmail, $toEmail)
{
// Render the email, use the first line as the subject, and the rest as the body
$renderedLines = explode("\n", trim($renderedTemplate));
$subject = array_shift($renderedLines);
$body = implode("\n", $renderedLines);
$message = (new \Swift_Message())
->setSubject($subject)
->setFrom($fromEmail)
->setTo($toEmail)
->setBody($body);
$this->mailer->send($message);
}
Also this works for sure:
public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['resetting.template'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()),
UrlGeneratorInterface::ABSOLUTE_URL);
$rendered = $this->templating->render($template, array(
'user' => $user,
'confirmationUrl' => $url,
));
$this->sendEmailMessageCustom($rendered, $this->from, (string)$user->getEmail(),'Password resseting');
}

Woocommerce Login Custome API Endpoint

I am developing an app using woocommerece store and using the Woocommerce REST API for Fetching the Products and Order details, but now I am facing the problem in login because Woocommerce didn't provide this type of API.
So I am creating a custom endpoint and trying this but I am getting the error 404, no rest route available.
Here is my custome end point which i registered.
add_action( 'rest_api_init', function () {
register_rest_route( 'wc/v2', '/login/)', array(
'methods' => 'POST',
'callback'=> 'my_awesome_func',
'args' => array(
),
) );
} );
Here is the login of Login but i think i am doing anything wrong at someplace so please check and help me .
function my_awesome_func( WP_REST_Request $request ) {
global $wpdb;
$username = $request['email'];
$password = $request['password'];
$db = new DbOperation();
$response = array();
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$results = $wpdb->get_row( "SELECT ID FROM rd_users WHERE user_email='".$username."'");
$activation_id = $results->ID;
$activation_key = get_user_meta( $activation_id, 'has_to_be_activated', true );
if($activation_key != false ){
$results = 2;//if activation key exists than show the error
}
else{
$user_verify = wp_signon( $login_data, false );
if ( is_wp_error($user_verify) )
{
$results = 0; //show invalid username and password.
}
else {
$results = 1; //login success.
}
}
if ($results== 1) {
$user_info = get_userdata($student[0]->ID);
$response['id'] = $user_info->ID;
$response['name'] = $user_info->display_name;
$response['fname'] = $user_info->first_name;
$response['lname'] = $user_info->last_name;
$response['email'] = $user_info->user_email;
$response['status'] = 1;
$response["error"] = false;
$response['message'] = "You have successfully Logedin!";
} else {
if($results == 0){
$response['status'] = 0;
$response["error"] = true;
$response['message'] = "Invalid username or password";
}
else{
$response['status'] = 2;
$response["error"] = true;
$response['message'] ="Your account has not been activated yet.
To activate it check your email and clik on the activation link.";
}
}
return $response;
}
See what i have found,
used https authentication. In postman, instead of using oAuth1.0 as the authentication, use Basic authentication and pass consumer key as the username. And the password should be consumer secret.
I hope that would work.

Validate wordpress password repeat with REST api

I have a registeration form with some custom fields and need to register users with Wordpress REST api,
$('#user_register_form').submit(function(e){
e.preventDefault();
var form = $(this),
rest = new DwREST();
rest.registerUser({
first_name: '',
last_name: '',
username: 'amin',
name : 'amin',
email : 'aaaa#amin.ev',
password: '11111',
// passwrod2: '11111' -confirm password field
// custom_field1: ''
// ....
}, function( res ){
console.log( res );
});
});
The user registeration works fine but the problem is i can't confirm wether password repeat matches or not, i searched a lot and didn't find an action to modify to /users/ validation
the second question is is it possible to automatically login user created with REST api after registeration?
i appreciate any help.
I searched in rest-api source codes, sadly i didn't find any proper hook to do what i needed, there's just a rest_pre_insert_user hook which getting it to do what i intend to do is a bit tricky, but here's the work around, in case some one has the same problem:
add_filter('rest_pre_insert_user', function( $user, $request ){
$params = $request->get_params();
if( $params['password'] !== $params['password2'] ) {
$error = new WP_Error( 'rest_no_matching_passwords', __( 'Passwords don\'t match' ), array( 'status' => 400 ) );
foreach( $error->error_data as $data ) {
http_response_code( $data['status'] );
}
header('Content-Type: application/json; charset=utf-8;');
foreach( $error->errors as $key => $val ){
$json = json_encode([
'code' => $key,
'type' => 'error',
'message' => $val[0]
]);
}
die( $json );
}
return $user;
}, 10, 2 );
Reference

Resources