Depending on your requirements that's quite easy to programm.
- Create a Module
- Register an Observer (Module/Name/etc/frontend/events.xml)
<?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_predispatch">
<observer name="module_name_force_login_route_observer" instance="Module\Name\Observer\ControllerActionObserver"/>
</event>
</config>
- And add an Observer with your custom logic redirecting to the login page.
<?php
namespace Module\Name\Observer;
use Magento\Framework\App\Response\Http;
use Magento\Framework\UrlFactory;
use Magento\Framework\App\Http\Context;
use Magento\Customer\Model\Context as CustomerContext;
class ControllerActionObserver implements ObserverInterface
{
const LOGIN_CONTROLLER_ACTION = 'customer/account/login';
protected $_response;
protected $_urlFactory;
protected $_context;
public function __construct(
Http $response,
UrlFactory $urlFactory,
Context $context
){
$this->_response = $response;
$this->_urlFactory = $urlFactory;
$this->_context = $context;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$request = $observer->getEvent()->getRequest();
$loggedIn = $this->_context->getValue(CustomerContext::CONTEXT_AUTH);
$group = $this->_context->getValue(CustomerContext::CONTEXT_GROUP);
if ( //Some Logic ) {
$url = $this->_urlFactory->create()->getUrl(self::LOGIN_CONTROLLER_ACTION)
$this->_response->setRedirect($url);
}
}
}
As an example your logic could look like this to redirect all customers who are not logged in from the product view to the login page.
if (!loggedIn && strtolower($request->getFullActionName()) === 'catalog_product_view')