Magento 2 - Chuyển hướng người dùng đến một trang cụ thể nếu chưa đăng nhập


8

Tôi cần chuyển hướng người dùng đến trang đích nếu chưa đăng nhập. Tôi tìm thấy một công việc tương tự trong liên kết này . Có một giải pháp cho Magento 2?

Câu trả lời:


21

Nếu chúng ta muốn bắt controller_action_predispatch, chúng ta có thể làm theo:

ứng dụng / mã / Nhà cung cấp / Mô-đun / etc / event.xml


     <event name="controller_action_predispatch">
            <observer name="check_login_persistent" instance="Vendor\Module\Observer\CheckLoginPersistentObserver" />
     </event>

ứng dụng / mã / Nhà cung cấp / Mô-đun / Quan sát viên / CheckLoginPersistentObserver.php

namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;


class CheckLoginPersistentObserver implements ObserverInterface
{
         /**
         * @var \Magento\Framework\App\Response\RedirectInterface
         */
        protected $redirect;

        /**
         * Customer session
         *
         * @var \Magento\Customer\Model\Session
         */
        protected $_customerSession;

        public function __construct(
            \Magento\Customer\Model\Session $customerSession,
            \Magento\Framework\App\Response\RedirectInterface $redirect

        ) {

            $this->_customerSession = $customerSession;
            $this->redirect = $redirect;

        }

        public function execute(\Magento\Framework\Event\Observer $observer)
        {
            $actionName = $observer->getEvent()->getRequest()->getFullActionName();
            $controller = $observer->getControllerAction();

            $openActions = array(
                'create',
                'createpost',
                'login',
                'loginpost',
                'logoutsuccess',
                'forgotpassword',
                'forgotpasswordpost',
                'resetpassword',
                'resetpasswordpost',
                'confirm',
                'confirmation'
            );
            if ($controller == 'account' && in_array($actionName, $openActions)) {
                return $this; //if in allowed actions do nothing.
            }
            if(!$this->_customerSession->isLoggedIn()) {
                $this->redirect->redirect($controller->getResponse(), 'customer/account/login');
            }

        }

}

2
if ($controller == 'account' && in_array($action, $openActions)) { return $this; //if in allowed actions do nothing. }mã này không bao giờ thực thi chúng là không có biến với hành động tên trong mã. cũng trong __construct (bạn đã đặt dấu "," ở cuối dẫn đến lỗi.
Ashish Madankar M2 Professiona

1
Làm thế nào để bạn tham khảo bộ điều khiển cụ thể của bạn cho điều này? Tôi đã sao chép mã nhưng không hiểu làm thế nào để kích hoạt nó khi bộ điều khiển của tôi bị tấn công.
harri

4

Để tối ưu hóa hơn và mã làm việc, bạn có thể làm theo các bước dưới đây.

  1. tạo tệp sự kiện @ app \ code \ Vendor \ Module \ etc \ frontend \ event.xml

    <?xml version='1.0'?>
    <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd'>
        <event name='controller_action_predispatch'>
            <observer
                    name='checklogin'
                    instance='Vendor\Module\Model\Observer'
            />
        </event>
    </config>
    
  2. Tạo ứng dụng tệp Observer \ code \ Vendor \ Module \ Model \ Observer.php

    namespace Vendor\Module\Model;
    
    class Observer implements \Magento\Framework\Event\ObserverInterface
    {
    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        # check if user is logged in
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->get('Magento\Customer\Model\Session');
        if(!$customerSession->isLoggedIn())
        {
            $request = $objectManager->get('Magento\Framework\App\Request\Http');
            //get instance for URL interface
            /** @var \Magento\Framework\UrlInterface $urlInterface */
            $urlInterface = $objectManager->get('Magento\Framework\UrlInterface');
            // URL to redirect to
            $url = $urlInterface->getUrl('customer/account/login');
            if(strpos($request->getPathInfo(), '/customer/account/') !== 0)
            {
                # redirect to /customer/account/login
                $observer->getControllerAction()
                    ->getResponse()
                    ->setRedirect($url);
            }
        }
    }

2

Có một giải pháp dễ dàng hơn nhiều. Nhìn vào tập tin này:

src / nhà cung cấp / magento / mô-đun bán hàng / etc / di.xml

<type name="Magento\Sales\Controller\Order\History">
    <plugin name="authentication" type="Magento\Sales\Controller\Order\Plugin\Authentication"/>
</type>

Vì vậy, bạn chỉ cần sử dụng plugin xác thực trong mô-đun di.xml của mình

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.