the community! I'm trying to implement a module that will prevent the customer from doing anything on the website before he'll set the value on the specific page. So until the customer didn't set that value - I want to redirect him only to my custom page. Do any of us implement something like this? Can you share your thoughts and give me an idea of how to move forward on that? I've built everything around that - attributes, page, and other stuff. I just don't know how to exactly prevent the customer to see anything once he logged in.
1 Answer
Finally found a solution.
You have to create around
plugin for a method dispatch
in a class Magento\Framework\App\FrontController
. Here how it all looks like:
di.xml:
<type name="Magento\Framework\App\FrontController">
<plugin name="PLUGIN_NAME_ID"
type="VENDOR\PLUGIN\Plugin\FrontControllerPlugin"/>
</type>
FrontControllerPlugin.php:
public function __construct(
\Magento\Framework\UrlInterface $url,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Customer\Model\Session $session
) {
$this->url = $url;
$this->responseFactory = $responseFactory;
$this->session = $session;
}
public function aroundDispatch(
\Magento\Framework\App\FrontController $subject,
Closure $proceed,
\Magento\Framework\App\RequestInterface $request
) {
if ($this->session->isLoggedIn() === true) {
$userHasAllValues = $this->customerHasAllValuesSet();
$pathInfo = $request->getPathInfo();
$inAllowedUrls = in_array($pathInfo, [
'/yourspecificurl/',
'/yourspecificurl/save'
], true);
if ($userHasAllValues === false && $inAllowedUrls === false) {
$redirectUrl = $this->url->getRedirectUrl('/yourspecificurl/');
$response = $this->responseFactory->create();
$response->setRedirect($redirectUrl, 302);
$response->setNoCacheHeaders();
return $response;
}
}
return $proceed($request);
}
/**
* Check if customer has all attributes filled
*
* @return bool
*/
protected function customerHasAllValuesSet()
{
$customer = $this->session->getCustomer();
if ($customer) {
$attribute1 = $customer->getData('attribute1');
$attribute2 = $customer->getData('attribute2');
if (!empty($attribute1) && !empty($attribute2)) {
return true;
}
}
return false;
}