Thursday, December 18, 2014

How to log in/out Magento user to Wordpress blog - II

In the previous article How to log in/out Magento user to Wordpress blog - I, we have discussed how we can create Wordpress user during Magento 1.8 customer sign-up. Now we would check how we can make the user log in/out into/from Wordpress when the user signs in/out to/from Magento 1.8. 

As Wordpress functions are not available within Magento, we need to create a normal PHP page where we can include Wordpress core classes and use Wordpress functions for log in/out. So, when we call custom_login_wp.php?username=chandan&password=test123, this file calls Wordpress methods to log the user into Wordpress. Similarly, when we call custom_login_wp.php?logout=1 it logs the user out from Wordpress.

Our Wordpress folder is "wp" inside the Magento installation. We are creating this file "custom_login_wp.php" inside the "wp" folder, but it can be created anywhere. 

Let's check out the code in custom_login_wp.php.

<?php
// Include the  Wordpress Core
require("wp-load.php");   

// LOG OUT

if( isset($_GET['logout']) && $_GET['logout']== 1)
{
    // Log Out existing user
  if ( is_user_logged_in() ) { wp_logout(); }
    
}

// LOG IN

// Find URL Parameters in the URL
if(isset($_GET['username']) && $_GET['username']!="" && isset($_GET['password']) && $_GET['password']!="")
{
  
  // Log Out existing user
  if ( is_user_logged_in() ) { wp_logout(); }

  // GET Login Data from URL

  $creds = array();
  $creds['user_login']    = $_GET['username'];
  $creds['user_password'] = $_GET['password'];
  $creds['remember'] = false;

  // Wordpress LOGIN method
  $user = wp_signon( $creds, false );

  // ERROR  
  if ( is_wp_error($user) )
  {
   echo $user->get_error_message(); 
  }
}

// Always return the user to where

// Magento wanted to redirect
header("location:" . $_GET['current_url'] );
?>

The last line is a redirect; we better redirect the user to a URL where Magento user goes after a successful log in. So, in that case we need to call the custom_login_wp.php as shown below ::

custom_login_wp.php?username=chandan&password=test123&current_url=http://example.com/customer/account

Check out the "current_url" parameter ... it specifies where to return within Magento after Wordpress Log in.

Some points to be noticed here :

1. To Log any Wordpress user out, we use Wordpress function wp_logout()
2. To check if any user is logged in, we use Wordpress function is_user_logged_in()
3. To Log a user in, we use Wordpress function wp_signon()

Next let's check out the "loginPostAction()" method in Mage Customer's AccountController.php file which is responsible for logging the user into Magento. We need to append our Wordpress Login code to this method. We just need to remember here that during Wordpress signup, we had used the user's Firstname as Wordpress username and user's Magento password as Wordpress password. Here is the loginPostAction() method. 

<?php
public function loginPostAction()
{
  ...

  try 
  {
    $session->login($login['username'], $login['password']);

    if ($session->getCustomer()->getIsJustConfirmed()) 
    {
  $this->_welcomeCustomer($session->getCustomer(), true);
    }

    ////*** OUR CUSTOM CODE STARTS HERE **////
    /// At this position, user is successfully
    /// Logged into Magento, Now it's our scope to
    /// log the user into Wordpress
    /// Let's get username and password

    $customer       = $session->getCustomer();
    $first_name     = $customer->getFirstname();
    $user_pwd       = $login['password'];

    /// Build URL to our custom page "custom_login_wp.php"
    $base_url = str_replace("/index.php","",Mage::getBaseUrl()) ;
    $target_url = $base_url . "wp/custom_login_wp.php?username=$first_name&password=$user_pwd&current_url=";

    // Check if Magento redirects to DashBoard
    $rdrct2Dashb = Mage::getStoreConfigFlag( Mage_Customer_Helper_Data::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD );

    // If Not DashBoard
    if(!$rdrct2Dashb)
    {
        $p = $base_url;
    }
    // Redirect to CUstomer DashBoard
    else
    {
        $p = "{$base_url}index.php/customer/account";
    }

    // Final URL is ready
    $target_url .= $p;


    //// REDIRECT User for a WORDPress Login
    if (!headers_sent()) 
    {
header( "Location:$target_url" ); exit;
    }
    ////*** OUR CUSTOM CODE ENDS HERE ***////

 } 
 catch (Mage_Core_Exception $e) 
 {
...
 } 
 catch (Exception $e) 
 {
...
 }

 ...
}
?>

Some points need to be noticed here : 

1. We take the Magento user's first name as Wordpress username. We get the user's first name with the statement $customer->getFirstname();
2. We extract the password user gives at Magento login prompt from the POST data stored in $login['password'].
3. In Magento Admin Panel, there is a provision to choose whether the customer will be redirected to Dashboard after login. So, we get that option's value by calling Mage::getStoreConfigFlag() with appropriate parameter. So, if that option is set to 'Yes', we would redirect the customer to Dashboard after we Log him into Wordpress (in custom_login_wp.php). Any other logic can be easily implemented here also.

Next, we would look into the Logout part. The Magento method logoutAction() inside Mage_Customer's AccountController.php file, is called when Magento user is logged out. So, we need to call the same file custom_login_wp.php we have written earlier with parameter "logout=1". 

Check out the code below. 

<?php
public function logoutAction()
{
  $this->_getSession()->logout()->renewSession();

  ///**** Our Custom Code Starts ****//
  /// LOG OUT the USER from WordPress also
  /// Build the URL
  $base_url = str_replace("/index.php","",Mage::getBaseUrl()) ;
  $return_url = rtrim($base_url,"/") . "/index.php/customer/account/logoutSuccess/";
  
  $target_url = $base_url . "wp/custom_login_wp.php?logout=1&current_url=" . $return_url;

  if (!headers_sent()) 
  {
  header( "Location:$target_url" ); exit;
  }
  
  ///**** Our Custom Code Ends ****//
  $this->_redirect('*/*/logoutSuccess');
}
?>

Hope this helps. Another thing, we should not modify core files. It is always a good practice to create our own module to do such custom coding. Check the article "How to override Customer Account controller in Magento 1.8" to see how we can create our own Customer module extending the original Mage Customer module.

No comments: