0

I have to redirect the user to our SSO login page ifhe is not logged-in during the checkout.

As suggested here, I added this check into my phtml file that overrides this vendor/magento/module-checkout/view/frontend/templates/onepage.phtml.

if(!$this->customerSession->isLoggedIn()) 

Debugging the code seems that this->customerSession is not present. So, how can I check if the user is logged-in into this phtml file?

1 Answer 1

1

Direct answer to your question : You dont, you should not check in phtml file.

customerSession is not available in block and this is normal, you can see which methods are available in here : https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Checkout/Block/Onepage.php

Important Advice: do not include any logic in templates, it is a very bad practice

Proper solution : for that purpose you can use a plugin to change the result of redirection to cart to force login page :

etc/frontend/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Controller\Index\Index">
        <plugin name="redirect_to_login_sso_instead_of_cart"
                type="Project\Sso\Plugin\Frontend\Checkout\Controller\Index\IndexPlugin" sortOrder="10"
                disabled="false"/>
    </type>
</config>

and then in Project\Sso\Plugin\Frontend\Checkout\Controller\Index\IndexPlugin :

<?php

declare(strict_types=1);

namespace Project\Sso\Plugin\Frontend\Checkout\Controller\Index;

use Magento\Checkout\Controller\Index\Index;
use Magento\Customer\Model\Session;
use Magento\Framework\Exception\SessionException;

class IndexPlugin
{

    /** @var Session */
    private $customerSession;

    public function __construct(
        Session $customerSession
    ) {
        $this->customerSession = $customerSession;
    }

    /**
     * @throws SessionException
     */
    public function afterExecute(
        Index $subject,
        $result
    ) {
        if (!$this->customerSession->isLoggedIn()) {
            $this->customerSession->authenticate();
        }
        return $result;
    }

}

Tested 100% works.

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.