5

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

14

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;
        };
    }
);
|improve this answer|||||
  • So, it is a Magento bug and you fixed it? – Khoa TruongDinh Sep 2 '16 at 16:27
  • Yes, this issue reproducing only when full page cache is disabled. – Ihor Sviziev Sep 3 '16 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 Apr 27 '17 at 6:46
  • I updated my post, thank you for getting it! – Ihor Sviziev Apr 28 '17 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 Jul 11 '18 at 18:44
6

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.

|improve this answer|||||
  • I saw that code, but frontend isn't sending request to server after login (account dashboard). – Ihor Sviziev Sep 2 '16 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'). – Khoa TruongDinh Sep 2 '16 at 12:43
  • You can update your full code lines of your custom module on your question. – Khoa TruongDinh Sep 2 '16 at 13:18
2
define(['Magento_Customer/js/model/customer'], 
    function(customer) {
        return Component.extend({
            someMethod: function () {
                if (customer.isLoggedIn()) {
                   //do smth
                } else {
                   //do smth
                }
            },
        });
    }
);
|improve this answer|||||
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

|improve this answer|||||
0

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);
            }
        });
    }
);
|improve this answer|||||
-3

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
 {
 } 
|improve this answer|||||
  • You described how to check it on server side, but my question about client side – Ihor Sviziev Jan 3 '17 at 12:34
  • please update with your answer, check logged in via js. – Anas Mansuri Aug 29 '19 at 5:47

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.