Question

How to find if a customer is logged in or not in Magento 2.

If the customer is logged in then how to get customer data from a session?

Was it helpful?

Solution

Following code you can check customer login or not anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

From controller

$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

OTHER TIPS

Important reminder: One should never call the Object Manager directly

Thus here's how to do it the clean way

In any class except templates

You first need to inject the following class in your constructor: /Magento/Customer/Model/Session :

protected $_customerSession;    // don't name this `$_session` since it is already used in \Magento\Customer\Model\Session and your override would cause problems

public function __construct(
    ...
    \Magento\Customer\Model\Session $session,
    ...
) {
    ...
    $this->_customerSession = $session;
    ...
}

Then in your class you can call the following:

if ($this->_customerSession->isLoggedIn()) {
    // Customer is logged in 
} else {
    // Customer is not logged in
}

In a template

It requires a bit more work in a template as you will have to setup a preference for the block that renders the template to do that the clean way:

<preference for="Block\That\Renders\The\Template"
            type="Vendor\Module\Block\Your\Custom\Block" />

Then in your custom block contrusctor you need to following the same dependency injection as for any class (explained above).

The extra step here is to create a public method that can be used in your template to check whether a customer is logged in or not

public function isCustomerLoggedIn()
{
    return $this->_customerSession->isLoggedIn();
}

Then in your template you can call:

if ($block->isCustomerLoggedIn()) {
    // Customer is logged in
} else {
    // Customer is not logged in
}

Alternative if the customer session is not initialized yet

There's another way of doing it which implies using Magento\Framework\App\Http\Context instead of Magento/Customer/Model/Session

Then you can call $this->_context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH) instead of $this->_customerSession->isLoggedIn() to check whether the customer is logged in or not.

However this method may give you different results, I suggest you read this great answer for more information: https://magento.stackexchange.com/a/92133/2380

It is possible via Magento\Framework\App\Http\Context or via Magento\Customer\Model\Session. However, the result may be different:

  • HTTP context is initialized earlier than customer session (but it does not matter since both are initialized in action controllers)
  • When PageCache module is on (probably always on production), keep in mind that as soon as layout generation started, customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages. It means that if you now check if the customer is logged in via the HTTP context, it will still say 'yes', but customer data will not be available in customer sessions anymore. So double-check is necessary before trying to access data in customer sessions. This can easily happen in the block, while is unlikely in action controller since you are not expected to generate layout manually there, it will be generated after-action controller returns an instance of ResultInterface

To eliminate any risk of described inconsistencies when PageCache on, consider using customer session, if it is already initialized (true for action controllers). Else use the HTTP context.

/** @var \Magento\Framework\App\ObjectManager $om */
$om = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\Http\Context $context */
$context = $om->get('Magento\Framework\App\Http\Context');
/** @var bool $isLoggedIn */
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);

None of these solutions worked for me. Some pages would appear to be logged in but others would not. It seems this is the bug:

https://github.com/magento/magento2/issues/3294

I ended up creating a helper which I could call in my templates:

<?php
namespace MyVendor\MyModule\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

/**
 * Created by Carl Owens (carl@partfire.co.uk)
 * Company: PartFire Ltd (www.partfire.co.uk)
 **/
class Data extends AbstractHelper
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Http\Context $httpContext
    ) {
        parent::__construct($context);
        $this->httpContext = $httpContext;
    }

    public function isLoggedIn()
    {
        $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
        return $isLoggedIn;
    }
}

Then I could use the helper in my templates like so:

<?php
$helper = $this->helper('MyVendor\MyModule\Helper\Data');

if ($helper->isLoggedIn()) {
    //show something
}

None of the solutions here worked for me reliably in Magento v2.1 with Full Page Cache and Varnish enabled in Production mode. I finally found a solution that worked 100% of the time with all caching enabled after getting the idea from vendor/magento/module-theme/view/frontend/templates/html/header.phtml. Here is my solution, which shows a "Sign In" link when the user is logged out and a "Sign Out" link when the user is logged in:

<li data-bind="scope: 'customer'">
  <!-- ko if: customer().firstname  -->
  <a href="<?php echo $this->getUrl('customer/account/logout'); ?>" style="display:none;" data-bind="style: {display:'inline'}"><?php echo __('Sign Out') ?></a>
  <!-- /ko -->
  <!-- ko ifnot: customer().firstname  -->
  <a href="<?php echo $this->getUrl('customer/account/login'); ?>" style="display:none;" data-bind="style: {display:'inline'}"><?php echo __('Sign In') ?></a>
  <!-- /ko -->
  <script type="text/x-magento-init">
  {
    "*": {
      "Magento_Ui/js/core/app": {
        "components": {
          "customer": {
            "component": "Magento_Customer/js/view/customer"
          }
        }
      }
    }
  }
  </script>
</li>

UPDATE: Since v2.1.5 this solution is no longer reliable. See issue 9156 for a solution.

To get user logged in at template, you can simply call helper in just one single line :

<?php $_loggedin = $this->helper('Magento\Checkout\Helper\Cart')->getCart()->getCustomerSession()->isLoggedIn(); ?>

<?php if( $_loggedin ) : ?>

     <div><!-- add your code --></div>

<?php endif; ?>

Another answer:

<?php $_loggedin = $block->getLayout()->createBlock('Magento\Customer\Block\Account\AuthorizationLink')->isLoggedIn() ?>
 <?php if( $_loggedin ) : ?>
   // your code
 <?php endif; ?>

What do you think?

There are a lot of answers out there that go something like this...

GET OBJECT MANAGER LOAD UP CLASS MODEL DO STUFF

This is the WRONG methodology to use in Magento2.0. In 2.0, the auto generated object factories are the way to go. You can inject them into your constructor in almost any class and use them. Example:

public function __construct(
            Context $context,
            CollectionFactory $cmspageCollectionFactory,
            array $data = [],
            CustomerFactory $customerFactory,
            SessionFactory $sessionFactory)
        {
            parent::__construct($context, $data);
            $this->_cmspageCollectionFactory = $cmspageCollectionFactory;
            $this->customerFactory = $customerFactory;
            $this->sessionFactory = $sessionFactory;
        }

        /**
         * @return \Stti\Healthday\Model\ResourceModel\Cmspage\Collection
         */
        public function getCmspages()
        {
            // First check to see if someone is currently logged in.
            $customerSession = $this->sessionFactory->create();
            if ($customerSession->isLoggedIn()) {
                // customer is logged in;
                //$customer = $this->customerFactory->create()->get
            }

I have get the best solution. It is based on authentication of customer. Some of the case customer session was not working, But every time my solution will work. Lets take a look.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Block\Account\AuthorizationLink');
if ($customerSession->isLoggedIn() == true) {
//your code.
} ?>

Thanks.

Fetching the logged status from Session model will not work in case you want to use it after enabling Magento default FPC cache, in that case, you should use SessionFactory instead.

Session is not initiated if FPC caching is enabled, details: https://github.com/magento/magento2/issues/3294#issuecomment-328464943

To solve this you have to use SessionFactory, for example:

/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSessionFactory;

public function __construct(
    ....
    \Magento\Customer\Model\SessionFactory $customerSessionFactory
    ....
) 
{
    ....
    $this->_customerSessionFactory = $customerSessionFactory;
    ....
}

public function getCustomerId(){
  $customer = $this->_customerSessionFactory->create();
  echo $customer->getCustomer()->getId();
}

Hello got answer here :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');

if ($customerSession->isLoggedIn()) {
    $customerSession->getCustomerId();  // get Customer Id
    $customerSession->getCustomerGroupId();
    $customerSession->getCustomer();
    $customerSession->getCustomerData();

    echo $customerSessionget->getCustomer()->getName();  // get  Full Name
    echo $customerSessionget->getCustomer()->getEmail(); // get Email
}

Source.

$customerSession = $objectManager->get('Magento\Customer\Model\Session');

Replaced get with create now works fine:

$customerSession = $objectManager->create('Magento\Customer\Model\Session');

This is also one of the solution "Check whether the Customer is Logged in or not in Magento2"

Try below code:

 $om = \Magento\Framework\App\ObjectManager::getInstance();
 $context = $om->get('Magento\Framework\App\Http\Context');
 $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
 if($isLoggedIn){
      echo "Yes Customer loggedin";
      echo "<pre>";print_r($context->getData()); 
 }

Try below code:

<?php
namespace YourCompany\ModuleName\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context);
    }

public function isLoggedIn() // You can use this fucntion in any phtml file
    {
        return $this->customerSession->isLoggedIn();
    }
}

For using above code in phtml file you can call isLoggedIn() function as:

<?php $helper = $this->helper('YourCompany\ModuleName\Helper\Data'); ?>
<?php if($helper->isLoggedIn()) : ?>
    logged in
<?php else : ?>
    not logged in
<?php endif; ?> 

Hope this help thanks.

Current worked solution (IMHO)

<?php

namespace My\Module\Helper\Data;

/**
 * @var \Magento\Framework\ObjectManagerInterface
 */
protected $objectManager;

/**
 * @var \Magento\Customer\Model\SessionFactory
 */
protected $customerSession;

/**
 * Class Data
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(
         \Magento\Framework\ObjectManagerInterface $objectManager
    )
    {
        $this->objectManager   = $objectManager;
        $this->customerSession = $this->objectManager->create('Magento\Customer\Model\SessionFactory')->create();
    }

    /**
     * @return \Magento\Customer\Model\SessionFactory
     */
    public function getCustomerSession()
    {
       return $this->customerSession;     
    }

    /**
     * @return bool
     */
    public function isCustomerLoggedIn()
    {
        return ($this->getCustomerSession()->isLoggedIn()) ? true : false;
    }
}

If you want to check customer logged in or not then use this code in phtml files,

$om = \Magento\Framework\App\ObjectManager::getInstance();
$appContext = $om->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $appContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if($isLoggedIn) {
    /** LOGGED IN CUSTOMER, this should work in template   **/
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');

if($customerSession->isLoggedIn()) {

}

Declare \Magento\Customer\Model\SessionFactory in construct of your class.

protected $customerSession;

public function __construct(
    \Magento\Customer\Model\SessionFactory $customerSession
) {
    $this->customerSession = $customerSession;
}

public function isLoggedIn() // You can use this function in phtml file
{
    return $this->customerSession->create()->isLoggedIn();
}

just add this script in your phtml file if you want to check using JS and change code in your if else

<script type="text/javascript">
    require(['jquery'], function($){
        jQuery(document).ready( function() {
            var isLoggedIn = jQuery('.authorization-link > a').attr('href').indexOf('/login')<0;
            
            if(isLoggedIn){
                
            }else{
                
            }
        });
    });
</script>

I tried many ways found on google but none of the solution works. SO I checked the core functionality and created a php file to check a customer is logged in or not without using the Object Manager.


            /**
         * Customer session
         * Module created by Web Technology Codes
         * Developed by Vinay Sikarwar
         * @var \Magento\Framework\App\Http\Context
         */
        protected $session;

        /**
         * Registration constructor.
         * @param Context $context
         * @param array $data
         */
        public function __construct(
            Context $context,
                    \Magento\Framework\Session\Generic $session,
            array $data
        )
        {
                    $this->_session = $session;
                    parent::__construct($context, $data);
        }

            /**
         * Checking customer login status
         *
         * @api
         * @return bool
         */
        public function isCustomerLoggedIn()
        {
            return (bool)$this->getCustomerId()
                && $this->checkCustomerId($this->getId())
                && !$this->getIsCustomerEmulated();
        }
    }

For more info check it here http://blog.webtechnologycodes.com/customer-loggedin-check-magento2

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top