4

I'm trying to check if admin is logged in on frontend in Magento 2 but I didn't find the way.

Some help?

1

My source below may some helpful.

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="backend_auth_user_login_success">
        <observer name="name_of_observer_for_backend_auth_user_login_success" instance="\Instance\Class\Name" />
    </event>
</config>

Then create the observer.

class BackendAuthUserLoginSuccess implements ObserverInterface
{
    const DEFAULT_SESSION_NAME_OF_FRONTEND = 'PHPSESSID';

    /**
     * (non-PHPdoc)
     * @see \Magento\Framework\Event\ObserverInterface::execute()
     */
    public function execute(\Magento\Framework\Event\Observer $observer) {
        if (! isset($_COOKIE[self::DEFAULT_SESSION_NAME_OF_FRONTEND])) return;
        $backSessionId = session_id();
        $frontendSessionId = $_COOKIE[self::DEFAULT_SESSION_NAME_OF_FRONTEND];
        session_write_close();
        session_id($frontendSessionId);
        session_start();
        $_SESSION['admin'] = [$backSessionId];
        session_write_close();
        session_id($backSessionId);
        session_start();
        return;
    }
}

Now after admin login then you can get admin session id by front-end session in $_SESSION['admin'], and you can use session_id($_SESSION['admin'][0]) switch session details and continue.

This code need front-end session id already created, so must add one iframe (src=frontend.anypage) to backend/auth/login page.

2

You can do it this way:

Every backend action controller have access to the $this->_auth variable which is an instance of \Magento\Backend\Model\Auth declared in the constructor of Magento\Backend\App\AbstractAction.

To check if an admin user is logged in you can use:

$this->_auth->isLoggedIn()

In your controller.

In case you're not working with a controller you can use Dependency Injection in your constructor:

protected $_session;

public function __construct(
    \Magento\Framework\Model\Context $context,
    \Magento\Backend\Model\Auth\Session $authSession
) {
    $this->_session = $authSession;

    parent::__construct($context);
}

And then call:

$this->_session->isLoggedIn()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.