It can be achieved with the help of an observer.
Follow the below steps to create an extension PHPCodez_Keeplogin for this task.
1) Declare a module.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="PHPCodez_Keeplogin" setup_version="0.0.1" /> </config>
2) Register a module.
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'PHPCodez_Keeplogin', __DIR__ );
3) Create frontend/event.xml file and add the below content.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="controller_action_postdispatch"> <observer name="Keeplogin_controller_action_postdispatch" instance="PHPCodez\Keeplogin\Observer\KeepCustomerLoginObserver" /> </event> </config>
4) Create an observer KeepCustomerLoginObserver.php
<?php namespace PHPCodez\Keeplogin\Observer; use Magento\Framework\Event\ObserverInterface; class KeepCustomerLoginObserver implements ObserverInterface { private $customerUrl; private $context; private $contextHttp; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Http\Context $contextHttp, \Magento\Customer\Model\Url $customerUrl ) { $this->context = $context; $this->customerUrl = $customerUrl; $this->contextHttp = $contextHttp; } public function execute(\Magento\Framework\Event\Observer $observer) { $controller_name = $this->context->getRequest()->getControllerName(); $action_name = $this->context->getRequest()->getActionName(); $isLoggedIn = $this->contextHttp->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH); if ($isLoggedIn) { return $this; } if ($controller_name === 'account' && ($action_name === 'login' || $action_name === 'loginPost' || $action_name === 'forgotpassword' || $action_name === 'createpassword' || $action_name === 'create' ) ) { return $this; } $customer_login_url = $this->customerUrl->getLoginUrl(); $this->context->getResponse()->setRedirect($customer_login_url); } }
5) Issue the following commands.
$ php bin/magento indexer:reindex $ php bin/magento setup:upgrade $ php bin/magento setup:di:compile $ php bin/magento setup:static-content:deploy -f $ php bin/magento cache:flush