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

Ihor Sviziev
  • 515
  • 1
  • 3
  • 13

9 Answers9

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;
        };
    }
);
Ihor Sviziev
  • 515
  • 1
  • 3
  • 13
  • So, it is a Magento bug and you fixed it? – Khoa TruongDinh Sep 02 '16 at 16:27
  • Yes, this issue reproducing only when full page cache is disabled. – Ihor Sviziev Sep 03 '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 06:46
  • I updated my post, thank you for getting it! – Ihor Sviziev Apr 28 '17 at 07:52
  • how does 'customerData' get injected into that function call? – Scott Jul 09 '18 at 18:12
  • 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
  • facing the same issue as @Scott said – Gery Sep 12 '18 at 04:45
  • @Gery I added a solution that managed to work for me using the requirejs mechanisms to load it. (if you need the syntax for that, let me know) – Scott Sep 21 '18 at 19:04
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.

Khoa TruongDinh
  • 32,054
  • 11
  • 88
  • 155
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);
            }
        });
    }
);
Joel Davey
  • 680
  • 5
  • 14
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>

Asad Ullah
  • 1,461
  • 9
  • 24
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

Scott
  • 273
  • 1
  • 12
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');
    }             
});
MgtWizards
  • 523
  • 4
  • 10
-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
 {
 }