10

How to check that customer is logged in? In authentication-popup.js I found following code:

define([..., 'Magento_Customer/js/customer-data',...], 
    function(..., customerData, ...) {
        return Component.extend({
            ...
            /** Is login form enabled for current customer */
            isActive: function () {
                var customer = customerData.get('customer');
                return customer() == false;
            },
        });
    }
);

I copied it to my module, but it seems like isn't works, it still returns false after login.

Any ideas?

Env: - Magento 2.1.1 - Magento/blank theme

9 Answers 9

20

Magento 2.1.1 has an issue when full page cache is disabled - customer data isn't updating after success login. Details

Also sometimes customer data can be still not loaded (waiting for response), so in order to catch this case I prepared following code:

/**
 * This file will check that customer is logged in
 */
define(
    ['jquery', 'Magento_Customer/js/customer-data'],
    function ($, customerData) {
        'use strict';

        var getCustomerInfo = function () {
            var customer = customerData.get('customer');

            return customer();
        };

        var isLoggedIn = function (customerInfo) {
            customerInfo = customerInfo || getCustomerInfo();

            return customerInfo && customerInfo.firstname;
        };

        return function () {
            var deferred = $.Deferred();
            var customerInfo = getCustomerInfo();

            if (customerInfo && customerInfo.data_id) {
                deferred.resolve(isLoggedIn(customerInfo));
            } else {
                customerData.reload(['customer'], false)
                    .done(function () {
                        deferred.resolve(isLoggedIn());
                    })
                    .fail(function () {
                        deferred.reject();
                    });
            }

            return deferred;
        };
    }
);
8
  • So, it is a Magento bug and you fixed it? Commented Sep 2, 2016 at 16:27
  • Yes, this issue reproducing only when full page cache is disabled. Commented Sep 3, 2016 at 18:35
  • 2
    With this module you cannot handle failed conditions correctly, e.g.: getLoggedInStatus().then(function(sFirstName) { console.log(sFirstName ? 'Logged in' : 'Not logged in'); }).fail(function() { console.log('Failed to get customer data'); });. Fix: change deferred.fail() to deferred.reject().
    – thdoan
    Commented Apr 27, 2017 at 6:46
  • I updated my post, thank you for getting it! Commented Apr 28, 2017 at 7:52
  • 1
    OK, I tried implementing this and it's dying in 'getFromServer' in customer-data.js at the return when it's trying to reference options.sectionLoadUrl because options is undefined.
    – Scott
    Commented Jul 11, 2018 at 18:44
7
define(['Magento_Customer/js/model/customer'], 
    function(customer) {
        return Component.extend({
            someMethod: function () {
                if (customer.isLoggedIn()) {
                   //do smth
                } else {
                   //do smth
                }
            },
        });
    }
);
5

Navigate to:

vendor/magento/module-customer/CustomerData/Customer.php

public function getSectionData()
    {
        if (!$this->currentCustomer->getCustomerId()) {
            return [];
        }
        $customer = $this->currentCustomer->getCustomer();
        return [
            'fullname' => $this->customerViewHelper->getCustomerName($customer),
            'firstname' => $customer->getFirstname(),
        ];
    }

As we can see, this method will check the exist of customer. And then, it will return the fullname and lastname.

Local storage:

enter image description here

Basicall, your script can be:

        isActive: function () {
            var customer = customerData.get('customer');
            if(customer().fullname && customer().firstname)
            {
                return true;
            }
            return false;
        },

Technically, we can add a login flag to in customer data by overriding the customer data.

3
  • I saw that code, but frontend isn't sending request to server after login (account dashboard). Commented Sep 2, 2016 at 12:40
  • I'm not sure about your code, however, we can get the customer data from local storage localStorage.getItem('mage-cache-storage'). Commented Sep 2, 2016 at 12:43
  • You can update your full code lines of your custom module on your question. Commented Sep 2, 2016 at 13:18
2

For Magento >2.1.* versions, if customer is logged in then we get firstname, fullname & websiteId information in mage-cache-storage.

So to retrieve customer data, use 'Magento_Customer/js/customer-data' in your JS file's require arra. Following is the sample code:

define([ 'Magento_Customer/js/customer-data'], function(customerData) {
    'use strict';

    return {
        /**
         * Get customer local storage cache data
         */
        var customer = customerData.get('customer')();

        if (customer.fullname && customer.firstname)
        {
            return true;
        }

        return false;
    }
});
1

This is because the data may not be loaded yet. You could use this approach:

define([..., 'Magento_Customer/js/customer-data', 'ko', ...], 
    function(..., customerData, 'ko', ...) {
        return Component.extend({
            ...
            /** Is login form enabled for current customer */
            isActive: ko.observable(false),
            initialize: function () {

                var customer = customerData.get('customer');
                var _self = this;
                customer.subscribe(function (data) {
                    if(data.firstname) {
                       _self.isActive(true);
                    }
                }, this);
            }
        });
    }
);
1
  • Thank you so much it is perfect working for me. and i think this is perfect solution. Commented Oct 14, 2023 at 11:01
1

just add this script in your phtml file 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>
1
  • 1
    Sometimes we need straight and shorten way. Commented Jul 26, 2022 at 5:43
0

I ended up getting it to work with the following:

define([
    "jquery",
    "Magento_Customer/js/model/customer",
    "mage/cookies"
], function ($, customer) {
    "use strict";
    return function regpopup() {
        var loggedIn = (typeof(isLoggedIn) == 'boolean') ? isLoggedIn : customer.isLoggedIn();
        var regMsgSeen = ($.mage.cookies.get('regMsgSeen') == 1);

        var isRegPage = /\/customer\/account\/create/.test(window.location.pathname);

        if(!regMsgSeen && !loggedIn && ! isRegPage) {
            $(document).ready(
                function () {
                    $.mage.cookies.set('regMsgSeen',1,{});
                    setTimeout(
                        function () {
                            // only open register dialogue if login modal is not open
                            if($("#zoo-login-form").closest("aside").hasClass('_show') == false) {
                                $('div#zoo-register-form').modal('openModal');
                            }
                        }, 1000);
                });
        }
    }
});

Then added the file under my theme's web/js folder, added a reference to the file in the theme's requirejs-config.js

0

Just paste this at browser console and should return customer logged in or not logged in status.

require(['jquery', 'Magento_Customer/js/customer-data'], function ($, customerData) {
    var customer = customerData.get('customer')();
    if (customer.fullname && customer.firstname)
    {
        console.log('logged in');
    } else {
        console.log('NOT logged in');
    }             
});
-4

To check customer is logged in or not, try the below code.

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

if($customerSession->isLoggedIn()) 
 {
 // Your code
 }

else
 {
 } 
2
  • You described how to check it on server side, but my question about client side Commented Jan 3, 2017 at 12:34
  • please update with your answer, check logged in via js. Commented Aug 29, 2019 at 5:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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