4

I'm trying to login a user by ID but having issues with them staying logged in.

The user gets redirected to their account page but as soon as they click any link, they're not logged in. I am seeing a frontend cookie being set as well.

I am extending the Account Controller and here is my loginPostAction() method. Everything works except for the session.

require_once('Mage/Customer/controllers/AccountController.php');
class Silk_Casauth_AccountController extends Mage_Customer_AccountController {

    /**
     * Checks if the customer is logged into CAS, if not takes them to login.
     */
    public function loginAction() {
        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }

        if(phpCAS::isAuthenticated()) {
            $this->loginPostAction();
        } else {
            phpCAS::forceAuthentication();
        }
    }

    /**
     * Customer logout action
     */
    public function logoutAction() {    
        $this->_getSession()->logout()->setBeforeAuthUrl(Mage::getUrl());
        phpCAS::logout();
    }

    /**
     * Login post action
     */
    public function loginPostAction() {

        // Customer is logged in so lets redirect them to where the need to go
        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }

        unset($_COOKIE['session_for%3Aindex_php']);

        $r = $this->getRequest()->getParam('r');
        $sid = $this->getRequest()->getParam('SID');
        $session = $this->_getSession();

        $email = phpCAS::getUser();
        $uuid = KomApi::api()->get_user_by_email($email)->uuid;

        // Looking up the user account in Magento
        $customer = Mage::getModel('customer/customer')->getCollection();
        $customer->addAttributeToSelect('uuid')->addAttributeToFilter('uuid', $uuid)->load()->getFirstItem()->getData();

        foreach ($customer as $cust) {
            $customer_id = $cust->getId();
        }

        if ($customer_id) {

            // Lets update the customer data
            $customer = Mage::getModel('customer/customer')->load($customer_id);
            $customer->set_name_email_from_kvo($uuid);

        } else {

            // This is a new customer in Magento so lets create the account
            $customer = Mage::getModel('customer/customer')->setId(null);
            $customer->create_user_from_kvo($uuid);

            $customer_id = $customer->getId();

            // Show the welcome message the first time a customer logs in
            $this->_welcomeCustomer($session->getCustomer(), true);
        }

        $customer = Mage::getModel('customer/customer')->load($customer_id);
        $customer->delete_all_addresses();
        $customer->create_addresses_from_kvo($uuid);

        // Log the customer in
        $session->setCustomerAsLoggedIn($customer);

        // Redirect back through this loop to be caught at the begining of the method
        $this->_loginPostRedirect();
    }

    /**
     * Customer create redirect to club
     */
    public function createAction() {
        $this->_redirectUrl(Mage::getModel('core/variable')->loadByCode('club_base_uri')->getValue('plain') . "/signup/?r=" . Mage::getBaseUrl() . "customer/account/");
    }

}

When I dump $session->loginById($customer_id) it returns true so it seems that part is working.

Edit with config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Silk_Casauth>
            <version>0.1.0</version>
        </Silk_Casauth>
    </modules>
    <frontend>
        <routers>
            <customer>
                <args>
                    <modules>
                        <Silk_Casauth before="Mage_Customer">Silk_Casauth</Silk_Casauth>
                    </modules>
                </args>
            </customer>
        </routers>
    </frontend>
    <global>
       <models>
          <customer>
              <rewrite>
                  <customer>Silk_Casauth_Model_Customer</customer>
              </rewrite>
          </customer>
       </models>
    </global>
</config>

I did some more testing and found that the default Magento login wasn't working either so I started messing with my config.xml file for this and found that if I remove frontend and everything in it that the default Magento login works correctly.

I have looked through my code and other examples and from what I gather I have everything correct. I'm not sure where to go from here.

EDIT: It doesn't look like it's the config.xml file. When I made my changes to the core controller I was getting the same issue. I have updated above with the entire controller that I'm using.

More digging and I found in Magento's system.log Warning: include(CAS/Client.php): failed to open stream: No such file or directory in /var/www/domain.com/app/lib/Varien/Autoload.php on line 93. So it seems that when I inlude the files above the class that Magento's autoloader is trying to load CAS but the path is wrong. I'm not sure how to go about this now.

Latest Edit: I've required the CAS files in Magento's index.php file and that seems to have solved the issue but seems like a really dirty way of doing it.

  • When the user is logged out is the frontend cookie purged. Does is contain logged in status. Your code is the same that i use and have no issues. – James Cowie Sep 5 '14 at 20:01
  • I'm clearing all cookies before I try logging in but the frontend cookie is not being deleted when I logout. The logout method has this code $this->_getSession()->logout()->setBeforeAuthUrl(Mage::getUrl()); – kel Sep 5 '14 at 20:55
  • The frontend cookie will remain when logging out has it has more info contained. Can try try mage logging the is logged in method on session and see what the session believes the state is. Ill load a vm later and test for you. What version of magento are you using. – James Cowie Sep 5 '14 at 22:18
  • http / https issue ? – Amasty Sep 10 '14 at 9:47
  • @Amasty I do see that when I am on the account page its https but when I click a link its http. I'm not sure why the session would drop because of that though. In the config I have Use HTTP Only set to yes for cookies and Use Secure URLs in Frontend is set to yes as well. Is there any way to make everything https when a user signs in? – kel Sep 10 '14 at 22:57
0

This Code seem Incorrect

$customer = Mage::getModel('customer/customer')->getCollection();
$customer->addAttributeToSelect('uuid')->addAttributeToFilter('uuid', $uuid)->load()->getFirstItem()->getData();

foreach ($customer as $cust) {
    $customer_id = $cust->getId();
}

->getFirstItem() return first item from a collection, so no need to loop

->getData() should return an array so you can not do $cust->getId() (array not object)

Take a look at Login as a Customer from Magento Admin

//Please hard code $uuid to rule out any error in KomApi and phpCAS class
$uuid = "xyz";


$customer = Mage::getModel('customer/customer')->getCollection()
                ->addFieldToFilter('uuid', $uuid)
                ->load()
                ->getFirstItem(); //to-do check the out come of getFirstItem() if collection is empty

if(!$customer->getId()){
   //customer not found for udid
   return;
}

$session = Mage::getSingleton('customer/session');
//$id = (int) trim($this->getRequest()->getParam('customerid'));

try{
    if($id){
       //$customer = Mage::getModel('customer/customer')->load($id);
       $session->setCustomerAsLoggedIn($customer);
       $message = $this->__('You are now logged in as %s', $customer->getName());
       $session->addNotice($message);
       Mage::log($message);
     }else{
       throw new Exception ($this->__('The login attempt was unsuccessful. Some parameter is missing'));
     }
}catch (Exception $e){
    $session->addError($e->getMessage());
}

$this->_redirect('customer/account');

The above code work in 1.7. with ssl enable and executing it from a non ssl page without any cookie issue when redirect to customer account page*

3

This code works well in our module:

$session = Mage::getSingleton('customer/session');
$session->renewSession()
    ->loginById($customerId);
$this->_redirect('customer/account/');

EDIT:
As there is HTTP / HTTPs switch (as described in the comments), you may also check the suhosin Apache module settings. Set

suhosin.session.encrypt = Off

For IIS there is also a setting under ASP > Session Properties > New ID on secure Connection.

  • This didn't work for me. – kel Sep 9 '14 at 19:30
  • This works perfectly! – Liam McArthur Nov 4 '16 at 10:06
  • renewSession is probably not even needed, since this is executed by setCustomerAsLoggedIn which is executed by loginById. – fritzmg Dec 19 '16 at 13:57
1

If you have customer email id and you want to login without password by code Here the code to login customer in magento programmatically without password

$email = 'test@m2s.com';
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail(trim($email));
Mage::getSingleton('customer/session')->loginById($customer->getId());
0

I would try to shut down the web server for a minute. Then, clean the session storage from cmd line (which one are you using : Db ? filesystem ?) Then I'll try your code and monitor if the session is created correclty. I'll also check if the session token (or file if you use filesystem) is still there once you click on a link somewhere after login in....

That may help you figure out where the session problem occurs, because according to your investigation, that's where I would have a look.

0
<?php
    require_once "app/Mage.php";
    Mage::app('default');
    umask(0);
    Mage::getSingleton('core/session', array('name' => 'frontend'));

    $session = Mage::getSingleton('customer/session');

$session->start();

            if (!empty($email) && !empty($password )) {
                    try {
                        $session->login($email, $password );
                        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 = Mage::helper('customer')->getEmailConfirmationUrl($email);
                                $message = Mage::helper('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($email);
                    } catch (Exception $e) {
                        // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
                    }
                } else {
                    $session->addError('Login and password are required.');


   }
?>

I am trying to programmatically login,it successful but in product details page get error like that
WHOOPS, OUR BAD...

The page you requested was not found, and we have a fine guess why. If you typed the URL directly, please make sure the spelling is correct. If you clicked on a link to get here, the link is outdated.

0
public function loginUser( $email, $password )
{
    /** @var $session Mage_Customer_Model_Session */
    $session = Mage::getSingleton( 'customer/session' );

    try
    {
        $session->login( $email, $password );
        $session->setCustomerAsLoggedIn( $session->getCustomer() );
        return true;
    }
    catch( Exception $e )
    {
        return false;
    }
}


/*Or you can try this*/
public function test()
{
$custSessionId='';

    if ($session->isLoggedIn()) {
        //The following gives you the session id for that customer.
        $custSessionId = Mage::getModel("core/session")->getEncryptedSessionId();
    }

    // Redirect to shop home page
    Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . '?SID=' . $custSessionId)->sendResponse();
}

/*
Or You can see the Magento default code to set the customer session this will help you.*/



public function loginPostAction()
{
    if ($this->_getSession()->isLoggedIn()) {
             $this->_redirect('*/*/');
             return;
         }
         $session = $this->_getSession();
         if ($this->getRequest()->isPost()) {
             $login = $this->getRequest()->getPost('login');
                     $session->login($login['username'], $login['password']);
                     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 = Mage::helper('customer')->getEmailConfirmationUrl($login['username']);
                $message = Mage::helper('customer')->__('This account is not confirmed. Click here 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();
     }


/*And Also one another solution...Load customer and*/

//Mage::getSingleton('customer/session')->loginById($customer->getId());
  • I'm using the loginById method and it doesn't work and I've also tried the login method with a user/pass. No luck. – kel Sep 10 '14 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.