1

I have the following code to see if a user is logged in. It sort of works as in it works within the customer area (user logged in) but doesn't work outside of the customer area even though the customer is still logged in.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) { ?>
   <li class="link wishlist" data-bind="scope: 'wishlist'">
    <a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?>
        <!-- ko if: wishlist().counter -->
        <span data-bind="text: wishlist().counter" class="counter qty"></span>
        <!-- /ko -->
    </a>
</li>
<li>Hello World</li>
?>
<?php
}
else {
?>
    <li>Not logged in</li>
<?php
}
?>



<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "wishlist": {
                        "component": "Magento_Wishlist/js/view/wishlist"
                    }
                }
            }
        }
    }

</script>
1

using the objectManager directly is highly discouraged and should be used only for testing purposes. You should use DI in your Controller.

See How to Set, Retrieve and Unset Session Variables in Magento 2? for more info.

Try this way and check if your problem persists.

1

you can change:

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

to:

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

worked for me

0

Below code is working for me.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   echo "Customer logged in";
}else{
    echo "Not customer logged in";
}

You can check code on this blog.

http://www.tilkor.com/blog/magento-2-check-customer-logged-in/

0

The customer and admin sessions are handled separately by Magento (two different session cookies), so in the admin area you do not have access to the customer session and vice versa.

You could try to achieve it by reading directly from the session storage. Example implementation for Magento 1: https://github.com/astorm/Magento_CrossAreaSessions

Alternatively it might work for you to make an AJAX request to the frontend and do your check there (Related: https://magento.stackexchange.com/a/7232/243)

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.