0

The below code works in Magento 1.

Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$adminSession = Mage::getSingleton('admin/session');
if ($adminSession->isLoggedIn()) {
  $adminIpAddress = $adminSession['_session_validator_data']['remote_addr'];
}

I am trying below code in magento 2 that is working in admin section but not working on front end

 $adminSession= $this->auth->isLoggedIn();
    including (\Magento\Backend\Model\Auth)

I need to check if admin is logged in or not on front end in magento2

Any help will be appreciated.

sv3n
  • 11,657
  • 7
  • 40
  • 73

1 Answers1

0

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.

Source :
Magento 2 How to check if Admin Logged on frontend
Check for more details.

There is answer exactly for your problem ;)

Konrad Siamro
  • 1,457
  • 1
  • 17
  • 29
  • 1
    I've tried this.It's not working as I want.Session is being created and saved when admin logged in but how to get on front-end and if admin logout then what will happen.This above code is just creating and saving session when admin login. – Priyanka Garg Feb 24 '17 at 12:59
  • @PriyankaGarg have you found any solution? – Prashant Valanda Jan 31 '18 at 06:06