Im trying to create a small widget that gets the authenticated user from the actual web app, which is in python/django(hosted on example.com), and sets headers across subdomains(*.example.com). The users. The users logged in on example.com should be able to use WordPress(hosted on blog.example.com) without again having to register/login to wordpress. Here I am trying to autologin(without password for WordPress) those users on WordPress so they can write blogs. I have written a small shortcode that does the above thing. Though the user is logged in, the /wp-admin still redirects to the login page. Below is the shortcode I wrote:
<?php
echo "STARTED";
$url = "https://app.example.com/api/user_profile/?my=1";
$arguments = array(
'method' => 'GET',
'cookies' => $_COOKIE
);
$response = wp_remote_get($url, $arguments );
if ( !is_wp_error( $response ) ) {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
$final_user = array();
$userID;
$email;
$username;
foreach ( $data as $datapoint ) {
$email = $datapoint->email;
$username = $datapoint->username;
}
$user_exists = get_user_by("email", $datapoint->email);
if (!$user_exists){
$user_info = array();
$new_user_id = wp_create_user($datapoint->username, $datapoint->username, $datapoint->email);
$final_user = get_user_by("id", $new_user_id);
} else {
$final_user = $user_exists;
}
// Login the user now
foreach ( $final_user as $fuser ) {
$userID = $final_user->ID;
}
echo "<br/>uerID - ";
echo $userID;
$user = get_user_by("login",$username);
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID);
do_action( 'wp_login', $user->username, $user );
echo "<br/> inside done";
} else {
echo "Something went wrong";
}
echo "<br/>-----------done"
?>
Im not sure what is wrong with the above code. I want the user to access /wp-admin so they can write posts if they are loggedin on our webapp. We are making an API request to our web app from our wordpress(protected private API for our use only) to get authenticated users on our app. This is the first time wrote PHP code, so it's not production ready (will write the optimal code later). Any help would be very appreciated. Please do let me know if there is anything more I need to provide.