Link login of two completely separate wordpress websites - wordpress

I have two wordpress websites running on sub-domain of a server like http://first.mywebsites.net and http://second.mywebsites.net
They both are just like private sites, I can see the content of pages if I am logged in to the website otherwise redirected to the login page.
Now what I want is, if I am log in my first website and go to the link of second website in same browser then I am able to see the content of pages as a logged in user.
This must be happen only in a case when the user which is logged in first website having the same user(user registered with same mail id) in database of second website. As in case of my website, mostly users are registered with same mail id in both the websites.
Trying to achieve this by two approaches but still unable to get this by any of them :
Approach 1 : Adding a table to second website and save the user email and a auth key. Using curl to fetch the details and then logged in. This Approach is as mentioned in here : http://carlofontanos.com/auto-login-to-wordpress-from-another-website
But as I have mentioned it previous, that both the website is in my case are having private content, so in this case I am unable to fetch the details using curl. My code for curl is like :
$api_url = "http://second.mywebsites.net/autologin-api/";
// If you are using WordPress on website A, you can do the following to get the currently logged in user:
global $current_user;
$user_email = $current_user->user_email;
// Set the parameters
$params = array(
'action' => 'get_login_key', // The name of the action on Website B
'key' => '54321', // The key that was set on Website B for authentication purposes.
'user_email' => $user_email // Pass the user_email of the currently logged in user in Website A
);
// Send the data using cURL
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$gbi_response = curl_exec($ch);
curl_close($ch);
// Parse the response
parse_str($gbi_response);
print_r($gbi_response);
In this case I am not getting the response, My page redirect me to the login page of second website.
Approach 2 : Trying to do it with the use of cookies as I want to logged in to second website in same browser.
I have added a new cookie in my first website like :
global $current_user;
$user_email = $current_user->user_email;
if($user_email != ''){
$_COOKIE['current_user_mail_id'] = $user_email;
}
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
and added cookie is showing with the other cookies. But when I am checking this in my second website on same browser like :
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
The cookie which I have added in my first website is not showing on my second website.
I am not much familiar with cookies, setting auth cookies etc.
Please suggest a solution, how can I achieve this.

You can accomplished by using "Single Signon".
Instruction-
To simplify passing users between our systems I have created this PHP class
that you are welcome to use.
To check if a user is signed in:
$signon = new SingleSignon();
$userId = $signon->checkCookie();
if($userId){
// user is logged in and this is their id
}
else{
// user is not logged in or they are exipred
}
If the user is not logged in then use our api to login then use the following code if the api call is successful.
To set a user as logged in:
$signon = new SingleSignon();
$signon->setCookie($userId);
NOTE: You need to be using ssl for the cookie to be read.

I have gone through the solution provided by Gaurav and find a idea to make this possible for wordpress websites.
Place below mentioned code at the place where you want to put the link to go to your second website :
<?php global $current_user;
$user_email = $current_user->user_email;
$user_login = $current_user->user_login;
if($user_email != ''){
$email_encoded = rtrim(strtr(base64_encode($user_email), '+/', '-_'), '=');
$user_login_encoded = rtrim(strtr(base64_encode($user_login), '+/', '-_'), '=');
echo '<div class="dtNode">Link to second website</div>';
}?>
Now prepare a sso.php file and place it to the root installation of your second site where you want to logged in automatically. Now put the below code there :
<?php
require_once( 'wp-load.php' ); //put correct absolute path for this file
global $wpdb;
if(isset($_GET['key']) && !empty($_GET['key'])){
$email_decoded = base64_decode(strtr($_GET['key'], '-_', '+/'));
$username_decoded = base64_decode(strtr($_GET['detail'], '-_', '+/'));
$received_email = sanitize_text_field($email_decoded);
$received_username = sanitize_text_field($username_decoded);
if( email_exists( $received_email )) {
//get the user id for the user record exists for received email from database
$user_id = $wpdb->get_var($wpdb->prepare("SELECT * FROM wp_users WHERE user_email = %s", $received_email ) );
wp_set_auth_cookie( $user_id); //login the user
wp_redirect( 'http://second.mywebsites.net');
}else {
//register those user whose mail id does not exists in database
if(username_exists( $received_username )){
//if username coming from first site exists in our database for any other user,
//then the email id will be set as username
$userdata = array(
'user_login' => $received_email,
'user_email' => $received_email,
'user_pass' => $received_username, // password will be username always
'first_name' => $received_username, // first name willl be username
'role' => 'subscriber' //register the user with subscriber role only
);
}else {
$userdata = array(
'user_login' => $received_username,
'user_email' => $received_email,
'user_pass' => $received_username, // password will be username always
'first_name' => $received_username, // first name willl be username
'role' => 'subscriber' //register the user with subscriber role only
);
}
$user_id = wp_insert_user( $userdata ) ; // adding user to the database
//On success
if ( ! is_wp_error( $user_id ) ) {
wp_set_auth_cookie( $user_id); //login that newly created user
wp_redirect( 'http://second.mywebsites.net');
}else{
echo "There may be a mismatch of email/username with the existing record.
Check the users with your current email/username or try with any other account.";die;
}
}
die;
} ?>
Above code works for me, you can modify the code as per your needs. For more clear explanation, you can check here : http://www.wptricks24.com/auto-login-one-website-another-wordpress

Related

Wordpress one time access to password protected page

I am creating a wordpress page which is password protected. It holds a form which needs to be submitted after a timed period of 3h. After that period the user should be logged out, no matter wether he completed the form or not. He should not be able to log in again.
As of now I achieved to set a timer after which the content of the page disappears. Now I need a tool that prevents a particular user to log back in and resubmit the form. Users do not get registered on my site. I want to email them a password for the protected page.
I can't simply change the password after login because as of now the page is protected by one password that every potential user needs to use.
To me the easiest way to avoid relogin seems to be the issuing of one time passwords for this particular page, so upon request every user gets his own OTP.
I am looking for a plugin which generates a list of OTPs for a specific wp page.
Easy solutions are greatly appreciated, since I am not seasoned at coding!
THANK YOU FOR YOUR HELP. Everybody starts somewhere...😔
Something like this (not tested):
$token = $_GET[ 'token' ];
if( is_numeric( $token ) AND metadata_exists( 'post', get_the_ID(), 'token_' . $token ) ):
if( empty( get_metadata( 'post', get_the_ID(), 'token_' . $token, true ) ) )
update_metadata( 'post', get_the_ID(), 'token_' . $token, time() + ( HOUR_IN_SECONDS * 3 );
if( $stamp = get_metadata( 'post', get_the_ID(), 'token_' . $token, true ) < time() ):
echo 'Here goes your form';
echo 'You have ' . $stamp - time() . ' seconds.';
else:
echo 'nope';
delete_metadata( 'post', get_the_ID(), 'token_' . $token )
endif;
else:
echo 'nope';
endif;
So you just have to create a empty postmeta field like token_98751328475 and share the url like example.com/myformpage?token=98751328475.
I would probably create a confirmation page to start the timer so that it doesn't start on first call.

How Can I add Email Verification Functions For WooCommerce

I would like to add Email verification procedure when user registers in WooCommerce. WordPress then emails a verification link to user's email. If link is clicked, it then activates the user's account. How would I do that?
I have used the code provided by Amit Kayshap and refined it to include extra checks and functions like automatically logging a user in after their account has been activated, resulting in a much smoother user experience.
Update: Unlike the original code, this one will not require any existing user to confirm their email address as well.
Like the code I based it upon, it is designed to run on a WordPress installation running WooCommerce. It also works if you have disabled the standard WordPress registration page.
You'll need an empty page with the URL yoursite.com/verify/ that builds on a template that contains <?php wc_print_notices(); ?> within its content container. It'll replace the /sign-in/ destination from the original code and will handle almost all messages created by this code.
Next, add this code to your theme's functions.php:
function wc_registration_redirect( $redirect_to ) { // prevents the user from logging in automatically after registering their account
wp_logout();
wp_redirect( '/verify/?n=1'); // redirects to a confirmation message
exit;
}
function wp_authenticate_user( $userdata ) { // when the user logs in, checks whether their email is verified
$has_activation_status = get_user_meta($userdata->ID, 'is_activated', false);
if ($has_activation_status) { // checks if this is an older account without activation status; skips the rest of the function if it is
$isActivated = get_user_meta($userdata->ID, 'is_activated', true);
if ( !$isActivated ) {
my_user_register( $userdata->ID ); // resends the activation mail if the account is not activated
$userdata = new WP_Error(
'my_theme_confirmation_error',
__( '<strong>Error:</strong> Your account has to be activated before you can login. Please click the link in the activation email that has been sent to you.<br /> If you do not receive the activation email within a few minutes, check your spam folder or click here to resend it.' )
);
}
}
return $userdata;
}
function my_user_register($user_id) { // when a user registers, sends them an email to verify their account
$user_info = get_userdata($user_id); // gets user data
$code = md5(time()); // creates md5 code to verify later
$string = array('id'=>$user_id, 'code'=>$code); // makes it into a code to send it to user via email
update_user_meta($user_id, 'is_activated', 0); // creates activation code and activation status in the database
update_user_meta($user_id, 'activationcode', $code);
$url = get_site_url(). '/verify/?p=' .base64_encode( serialize($string)); // creates the activation url
$html = ( 'Please click here to verify your email address and complete the registration process.' ); // This is the html template for your email message body
wc_mail($user_info->user_email, __( 'Activate your Account' ), $html); // sends the email to the user
}
function my_init(){ // handles all this verification stuff
if(isset($_GET['p'])){ // If accessed via an authentification link
$data = unserialize(base64_decode($_GET['p']));
$code = get_user_meta($data['id'], 'activationcode', true);
$isActivated = get_user_meta($data['id'], 'is_activated', true); // checks if the account has already been activated. We're doing this to prevent someone from logging in with an outdated confirmation link
if( $isActivated ) { // generates an error message if the account was already active
wc_add_notice( __( 'This account has already been activated. Please log in with your username and password.' ), 'error' );
}
else {
if($code == $data['code']){ // checks whether the decoded code given is the same as the one in the data base
update_user_meta($data['id'], 'is_activated', 1); // updates the database upon successful activation
$user_id = $data['id']; // logs the user in
$user = get_user_by( 'id', $user_id );
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login, $user );
}
wc_add_notice( __( '<strong>Success:</strong> Your account has been activated! You have been logged in and can now use the site to its full extent.' ), 'notice' );
} else {
wc_add_notice( __( '<strong>Error:</strong> Account activation failed. Please try again in a few minutes or resend the activation email.<br />Please note that any activation links previously sent lose their validity as soon as a new activation email gets sent.<br />If the verification fails repeatedly, please contact our administrator.' ), 'error' );
}
}
}
if(isset($_GET['u'])){ // If resending confirmation mail
my_user_register($_GET['u']);
wc_add_notice( __( 'Your activation email has been resent. Please check your email and your spam folder.' ), 'notice' );
}
if(isset($_GET['n'])){ // If account has been freshly created
wc_add_notice( __( 'Thank you for creating your account. You will need to confirm your email address in order to activate your account. An email containing the activation link has been sent to your email address. If the email does not arrive within a few minutes, check your spam folder.' ), 'notice' );
}
}
// the hooks to make it all work
add_action( 'init', 'my_init' );
add_filter('woocommerce_registration_redirect', 'wc_registration_redirect');
add_filter('wp_authenticate_user', 'wp_authenticate_user',10,2);
add_action('user_register', 'my_user_register',10,2);
If you are running a multilingual site, you can make the code translation-ready very easily. Just change the text strings like this: __( 'Text you want to translate', 'your-theme' ) This allows translation plugins like WPML to add the string to a translation table in the your-theme text domain.
Note that any string containing a variable like .$url. will generate a new string every time a different user activates its function. To circumvent this (and prevent string spamming into your database), we can translate them directly in the code:
if(ICL_LANGUAGE_CODE=='de'){
wc_add_notice( __( 'German error message' ), 'error' );
} else {
wc_add_notice( __( 'English error message' ), 'error' );
}
In this example, the german message will be output if the user's language code is detected as de (Also works if it is a variation like de_DE_formal), else it will output the english message.
Edit: I updated the code to not require an existing user to retroactively confirm their email address.

Wordpress Automatic Login after Registration in Plugin

I have a plugin for registration process in wordpress. There was no password field but I created a password field and inserted the password instead of sending random password in emails. It is using wp_create_user function to create the user.
Now, I am trying to make the automatic login after registration but failed in it.
I tried the following function but failed in it. Please someone help.
wp_set_current_user($user_id); // set the current wp user
wp_set_auth_cookie($user_id); // start the cookie for the current registered user
wp_redirect(home_url());
Here is the process that I have been using, it's not complete but how I think that it must work.
$status = wp_create_user($username, $user_pass, $email);
$user_data = $wpdb->get_row("SELECT * FROM $users_table where user_login='$username' ");
$user_id = isset($user_data) ? $user_data->ID : 0;
if (is_wp_error($status)) {
$errors[] = language_code('USER_NAME_ALREADY_EXIST_PLEASE_TRY_ANOTHER_ONE');
} else {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( home_url() );
}
Try following code into your theme functions.php file,It will work
function auto_login_new_user( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( home_url() );
exit;
}
add_action( 'user_register', 'auto_login_new_user' );

How to Auto Login After Registration in WordPress with core php

I've been trying for days now to take users who have just registered to my WordPress site and automatically log them in and then redirect them to a URL of my choice.
By default, WordPress sends you a username and a password, then you must log in manually. This is a total pain. How can i overcome this.
I have my own registration page(core php page) which successfully adds users into DB. But the point is, i should avoid users to login again.
Once registration is done, it should automatically redirects to home page or profile page.
I am a newbie to wordpress functionalities. It would be grateful if someone(who have knowledge on core functionality of wordpress) at least suggests a way/solution.
Looking forward.
Thanks
// Add on function.php for Auto login after register and redirect to a home page. varified this code
function auto_login_new_user( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
$user = get_user_by( 'id', $user_id );
do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1]
wp_redirect( home_url() ); // You can change home_url() to the specific URL,such as "wp_redirect( 'http://www.wpcoke.com' )";
exit;
}
add_action( 'user_register', 'auto_login_new_user' );
Following is based on how WooCommerce creates a new user and logs him in:
$user_pass = esc_attr( $_POST['account_password'] );
$new_user_data = array(
'user_login' => $_POST['account_username'],
'user_pass' => $user_pass,
'user_email' => $_POST['account_email'],
'role' => 'subscriber'
);
$user_id = wp_insert_user( $new_user_data );
// Set the global user object
$current_user = get_user_by( 'id', $user_id );
// set the WP login cookie
$secure_cookie = is_ssl() ? true : false;
wp_set_auth_cookie( $user_id, true, $secure_cookie );
to redirect use wp_safe_redirect, e.g.
wp_safe_redirect( home_url( '/' ) );
exit;
Instead of touching core files... You can use this
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie;
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($user_id, true, $secure_cookie);
$user_info = get_userdata($user_id);
do_action('wp_login', $user_info->user_login, $user_info);
The function wp_create_user returns the just created user_id which you can use to create a cookie and log the user in. If you wish, you can redirect the logged in user to the profile or home page.
Thanks for your support guys..i did on my own with the following code..thanks for your time and support :)
<i>$getdetails= mysql_fetch_array(mysql_query("SELECT * FROM `wp_users` WHERE `ID`='$user_id'"));
$username=$getdetails['user_login'];
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ){
echo $user->get_error_message();
}else{
wp_redirect( home_url() );
}

Access User Meta Data on User Registration in Wordpress

I am attempting to carry out a few functions when a user registers on a wordpress site. I have created a module for this which carries out the following function:
add_action( 'user_register', 'tml_new_user_registered' );
function tml_new_user_registered( $user_id ) {
//wp_set_auth_cookie( $user_id, false, is_ssl() );
//wp_redirect( admin_url( 'profile.php' ) );
$user_info = get_userdata($user_id);
$subscription_value = get_user_meta( $user_id, "subscribe_to_newsletter", TRUE);
if($subscription_value == "Yes") {
//include("Subscriber.Add.php");
}
echo "<pre>: ";
print_r($user_info);
print_r($subscription_value);
echo "</pre>";
exit;
}
But it seems that i am not able to access any user meta data as at the end of this stage none of it is stored.
Any ideas how i execute a function once Wordpress has completed the whole registration process of adding meta data into the relevant tables too?
I attempted to use this:
add_filter('user_register ','tml_new_user_registered',99);
But with no luck unfortunately.
Thanks in advance!
I read at the action reference api page that the user id is passed as user ID. Try substituting your $user_id for $user_ID.
I don't think the user metadata is available at the point where this action hook is triggered. From the Codex
"Not all user meta data has been stored in the database when this action is triggered. For example, nickname is in the database but first_name and last_name are not (as of 3.9.1). The password has already been encrypted when this action is triggered."

Resources