Tuesday, April 28, 2015

How to create user concurrency in Magento

I had a requirement where my client was looking on user login concurrency. By default Magento don't have this feature. So i have created a module which will handle user concurrency. Please follow the code to do it.


Go to the following site and create your module in a quick way.
http://www.silksoftware.com/magento-module-creator/#.UvHRXfuMA3h

Now Create the following table
CREATE TABLE IF NOT EXISTS 'customer_login_tracking' (
  'email' varchar(100) NOT NULL,
  'session_id' varchar(200) NOT NULL,
  'login_time' int(11) NOT NULL,
  UNIQUE KEY 'customer_id' ('email')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now add the following code in your etc/config.xml (where my module name space is Mymodule and module is Custom)
  <frontend>     
         <routers>
          <custom>
            <use>standard</use>
              <args>
                <module>Mymodule_Custom</module>
                <frontName>newpassword</frontName>
              </args>             
          </custom>
          <customer>
            <args>
                <modules>
                    <Mymodule_Custom before="Mage_Customer_AccountController">Mymodule_Custom</Mymodule_Custom>
                </modules>
            </args>
          </customer>
        </routers>
 </frontend>

 Now i have created 2 controllers
Custom\controllers\AccountController.php

<?php

require_once(Mage::getModuleDir('controllers','Mage_Customer').DS.'AccountController.php');

class Mymodule_Custom_AccountController extends Mage_Customer_AccountController
{
   

    /**
     * Login post action
     */
    public function loginPostAction()
    {
       
        if (!$this->_validateFormKey()) {
            $this->_redirect('*/*/');
            return;
        }

        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $session = $this->_getSession();

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                       $resource = Mage::getSingleton('core/resource');
                       $readConnection = $resource->getConnection('core_read');
                       $writeConnection = $resource->getConnection('core_write');
                                             
                       $tableName2 = $resource->getTableName('customer_login_tracking');
                      
                       $login_check = $readConnection->fetchRow('SELECT * FROM ' . $tableName2.' WHERE email="'.$login['username'].'"');
                      
                       if(isset($login_check['session_id'])){
                           $value = Mage::getUrl('custom/index/Clearcustomersession/us/'.base64_encode($login['username']));
                           $message = $this->_getHelper('customer')->__('You are already login from other place. <a href="%s">Click here</a> to clear the session.', $value);
                           Mage::getSingleton('core/session')->addError($message);
                       }else{
                          if($session->login($login['username'], $login['password'])){
                              $query = 'INSERT INTO '.$tableName2.' SET email="'.$login['username'].'", session_id="'.$session->getEncryptedSessionId().'", login_time="'.time().'"';
                              $writeConnection->query($query); 
                          }
                          if ($session->getCustomer()->getIsJustConfirmed()) {                               
                                $this->_welcomeCustomer($session->getCustomer(), true);                                                                       
                          }
                       }
                   
                } catch (Mage_Core_Exception $e) {
                    switch ($e->getCode()) {
                        case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
                            $value = $this->_getHelper('customer')->getEmailConfirmationUrl($login['username']);
                            $message = $this->_getHelper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
                            break;
                        case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
                            $message = $e->getMessage();
                            break;
                        default:
                            $message = $e->getMessage();
                    }
                    $session->addError($message);
                    $session->setUsername($login['username']);
                } catch (Exception $e) {
                    // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
                }
            } else {
                $session->addError($this->__('Login and password are required.'));
            }
        }

        $this->_loginPostRedirect();
    }
   
     /**
     * Customer logout action
     */
    public function logoutAction()
    {
        $resource = Mage::getSingleton('core/resource');
        $tableName2 = $resource->getTableName('customer_login_tracking');
        $readConnection = $resource->getConnection('core_read');   
        $readConnection->query('DELETE FROM '.$tableName2.' WHERE email="'.$this->_getSession()->getCustomer()->getEmail().'"');
       
        $this->_getSession()->logout()
            ->renewSession();

        $this->_redirect('*/*/logoutSuccess');
    }

  
}


Custom\controllers\IndexController.php

<?php
class Mymodule_Custom_IndexController extends Mage_Core_Controller_Front_Action{
public function ClearcustomersessionAction(){       
         $email = base64_decode($this->getRequest()->getParam('us'));
         $resource = Mage::getSingleton('core/resource');
         $readConnection = $resource->getConnection('core_read');
         $tableName = $resource->getTableName('customer_login_tracking');       
         $result = $readConnection->fetchRow('SELECT * FROM ' . $tableName.' WHERE email="'.$email.'"');
         unlink(Mage::getBaseDir('session').'\sess_'.$result['session_id']);
         $readConnection->query('DELETE FROM '.$tableName.' WHERE email="'.$email.'"');
         Mage::getSingleton('core/session')->addSuccess('Your previous session has been remove. Please login again.');
         Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('customer/account'));
     }
}

  

No comments:

Post a Comment