2

How can i get the admin session in frontend.

   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $adminSession = $objectManager->create('Magento\Security\Model\AdminSessionsManager');
   print_r($adminSession->getCurrentSession()->getStatus());

I tried with above script but no luck!

3
  • Maybe you can check this related topic. Magento 2 How to check if Admin Logged on frontend
    – I. Munoz
    Aug 3, 2022 at 18:19
  • 1
    What you actually want to do ? Aug 4, 2022 at 9:52
  • 1
    If you can provide more details about your goal, I can try to advise with solution. You should understand that admin cookie writes (and allows) only to your backend path and you cannot get it in code on frontend. Possible to create additional cookie in admin for frontend and work with it, but anyway need to understand a goal, maybe possible to implement more nicely solution. Aug 7, 2022 at 22:53

3 Answers 3

3
+50

Here you want to get admin session data into the frontend. Both areas are different so we can not get admin current admin login session. For more about area click here. I give you the solution for it.

Try This Code

app/code/VendoreName/ModuleName

registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VendoreName_ModuleName',
    __DIR__
);

app/code/VendoreName/ModuleName/etc

module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VendoreName_ModuleName" setup_version="1.0.0" >
        <sequence>
            <module name="Magento_Backend"/>
        </sequence>
    </module>
</config>

app/code/VendoreName/ModuleName/etc

db_schema.xml

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="custom_admin_user" resource="default" engine="innodb" comment="Admin Active USER">
        <column xsi:type="smallint" name="id" padding="6" unsigned="false" nullable="false" identity="true" comment="ID"/>
        <column xsi:type="varchar" name="admin_id" nullable="false" length="25" comment="Admin ID"/>
        <column xsi:type="varchar" name="status" nullable="false" length="25" comment="Admin Active Status"/>
        <column xsi:type="smallint" name="checkout_time" padding="6" unsigned="false" nullable="false" comment="Admin Checkout Time"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="id"/>
        </constraint>
    </table>
</schema>

app/code/VendoreName/ModuleName/Model

ActiveAdminData.php

<?php

namespace VendoreName\ModuleName\Model;

use Magento\Framework\Model\AbstractModel;
use VendoreName\ModuleName\Model\ResourceModel\ActiveAdminData as ActiveAdminDataResourceModel;

class ActiveAdminData extends AbstractModel
{
    /**
     * @inheritdoc
     */
    protected function _construct()
    {
        $this->_init(ActiveAdminDataResourceModel::class);
    }
}

app/code/VendoreName/ModuleName/Model/ResourceModel

ActiveAdminData.php

<?php

namespace VendoreName\ModuleName\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class ActiveAdminData extends AbstractDb
{
    /**
     * @inheritdoc
     */
    protected function _construct()
    {
        $this->_init('custom_admin_user', 'id');
    }
}

app/code/VendoreName/ModuleName/Model/ResourceModel/ActiveAdminData

Collection.php

<?php

namespace VendoreName\ModuleName\Model\ResourceModel\ActiveAdminData;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use VendoreName\ModuleName\Model\ActiveAdminData as ActiveAdminDataModel;
use VendoreName\ModuleName\Model\ResourceModel\ActiveAdminData as ActiveAdminDataResourceModel;

class Collection extends AbstractCollection
{
    /**
     * @inheritdoc
     */
    protected function _construct()
    {
        $this->_init(
            ActiveAdminDataModel::class,
            ActiveAdminDataResourceModel::class
        );
    }
}

app/code/VendoreName/ModuleName/etc

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="custom_admin_session_status" instance="VendoreName\ModuleName\Observer\GetActiveAdminStatus" />
  </event>
</config>

app/code/VendoreName/ModuleName/Observer

GetActiveAdminStatus.php

<?php

namespace VendoreName\ModuleName\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class GetActiveAdminStatus implements ObserverInterface
{
    protected $authSession;
    protected $state;
    protected $getActiveAdmin;
    protected $userFactory;
    protected $registry;
    protected $request;

    public function __construct(
        \Magento\Backend\Model\Auth\Session $authSession,
        \Magento\Framework\App\State $state,
        \VendoreName\ModuleName\Model\ActiveAdminDataFactory $getActiveAdmin,
        \Magento\User\Model\UserFactory $userFactory,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->authSession = $authSession;
        $this->state = $state;
        $this->getActiveAdmin = $getActiveAdmin;
        $this->userFactory = $userFactory;
        $this->registry = $registry;
        $this->request = $request;
    }

    public function execute(Observer $observer)
    {
        $areaCode = $this->state->getAreaCode();
        /* Get active admin user */
        if ($areaCode == "frontend") {
            $activeAdmin = [];
            $activeUserData = $this->getActiveAdmin->create()->getCollection();
            $activeUserData->addFieldToFilter('status', '1');
            if ($activeUserData->count()) {
                foreach ($activeUserData as $activeUserKey => $activeUserVal) {
                    $adminData = $this->userFactory->create()->load($activeUserVal->getAdminId());
                    if ($adminData->hasData()) {
                        $activeAdmin[] = $adminData->toArray();
                    }
                }
            }
            $this->registry->register('active_admins', $activeAdmin);
        }
        /* Set active admin user */
        if ($areaCode == "adminhtml") {
            $fullActionName = $this->request->getFullActionName();
            if ($fullActionName != "adminhtml_auth_logout") {
                $AdminloginStatus = $this->authSession->isLoggedIn();
                if ($AdminloginStatus) {
                    $inActiveTime = 120;
                    $adminId = $this->authSession->getUser()->getUserId();
                    $activeUserData = $this->getActiveAdmin->create()->getCollection();
                    $activeUserData->addFieldToFilter('admin_id', $adminId);
                    // print_r($activeUserData->getData());
                    if ($activeUserData->count()) {
                        /* Update active admin user */
                        $activeUserData = $activeUserData->getFirstItem();
                        $activeUserData->setStatus('1');
                        $activeUserData->setCheckoutTime($inActiveTime);
                        $activeUserData->save();
                    } else {
                        /* Add new admin user */
                        $setActiveUser = $this->getActiveAdmin->create();
                        $setActiveUser->setAdminId($adminId);
                        $setActiveUser->setStatus('1');
                        $setActiveUser->setCheckoutTime($inActiveTime);
                        $setActiveUser->save();
                    }
                }
            } else {
                /* Logout admin user */
                $adminId = $this->authSession->getUser()->getUserId();
                $activeUserData = $this->getActiveAdmin->create()->getCollection();
                $activeUserData->addFieldToFilter('admin_id', $adminId);
                if ($activeUserData->count()) {
                    $activeUserData = $activeUserData->getFirstItem();
                    $activeUserData->setStatus('0');
                    $activeUserData->setCheckoutTime(0);
                    $activeUserData->save();
                }
            }
        }
    }

}

app/code/VendoreName/ModuleName/etc

crontab.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job instance="VendoreName\ModuleName\Cron\SetAdminStatus" method="execute" name="custom_admin_status">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

app/code/VendoreName/ModuleName/Cron

SetAdminStatus.php

<?php

namespace VendoreName\ModuleName\Cron;

class SetAdminStatus
{
    protected $getActiveAdmin;

    public function __construct(
        \VendoreName\ModuleName\Model\ActiveAdminDataFactory $getActiveAdmin
    ) {
        $this->getActiveAdmin = $getActiveAdmin;
    }

    public function execute()
    {
        $activeUserData = $this->getActiveAdmin->create()->getCollection();
        $activeUserData->addFieldToFilter('status', '1');
        foreach ($activeUserData as $activeUserKey => $activeUserVal) {
            $checkoutTime = intval($activeUserVal->getCheckoutTime() - 1);
            if ($checkoutTime <= 0) {
                $activeUserVal->setCheckoutTime('0');
                $activeUserVal->setStatus('0');
            } else {
                $activeUserVal->setCheckoutTime($checkoutTime);
            }
            $activeUserVal->save();
        }
    }
}

app/code/VendoreName/ModuleName/view/frontend/layout

default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="main.content">
            <block class="VendoreName\ModuleName\Block\GetActiveAdmins" name="get.active.admin" before="-" template="VendoreName_ModuleName::adminlist.phtml" />
        </referenceContainer>
    </body>
</page>

app/code/VendoreName/ModuleName/Block

GetActiveAdmins.php

<?php

namespace VendoreName\ModuleName\Block;

class GetActiveAdmins extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->registry = $registry;
        parent::__construct($context, $data);
    }

    public function getActiveAdmin()
    {
        return $this->registry->registry('active_admins');
    }
}

app/code/VendoreName/ModuleName/view/frontend/templates

adminlist.phtml

<?php
echo "<pre>";
echo "<br>Call From Helper<br>";
$helperClass = $this->helper(\VendoreName\ModuleName\Helper\Data::class);
print_r($helperClass->getActiveAdmin());
echo "<br>Call From Block<br>";
print_r($block->getActiveAdmin());
echo "</pre>";
?>

app/code/VendoreName/ModuleName/Helper

Data.php

<?php

namespace VendoreName\ModuleName\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $registry;

    public function __construct(
        \Magento\Framework\Registry $registry
    ) {
        $this->registry = $registry;
    }

    public function getActiveAdmin()
    {
        return $this->registry->registry('active_admins');
    }
}

When the admin is login then its status is going to active and if he/she sign out then its status goes to inactive. and also if the admin user is login and does not have any activity by admin then its status goes to inactive. In the Observer GetActiveAdminStatus.php file you can set your time what you want

3
  • how can I get the user session on the frontend if I'm logged in and have access to the admin cookie for the admin user? Something like $user = $this->backendUserModel->getById or getBySessionId() I want the data equivalent to like what you get here for "user" if using the event vendor/magento/module-backend/Model/Auth.php:169 ['user' => $this->getCredentialStorage()] Aug 8, 2022 at 6:19
  • @KevinChavez you can store admin cookie data in the custom_admin_user table by adding a new column. and get them in the front end by using the above code.
    – Msquare
    Aug 8, 2022 at 6:43
  • @KevinChavez you can also add your data into nimb.ws/vh6ayo array and get them using Registry. Data must be store into our table.
    – Msquare
    Aug 8, 2022 at 6:57
1

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>

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;
    }
}
</config>
-2
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()

Note: don't use objectManager directly in the code. Its not proper way to do it in Magento 2.

3
  • no luck and \Magento\Framework\App\Action\Context $context instead of \Magento\Framework\Model\Context $context,
    – Ramesh
    Sep 28, 2017 at 16:02
  • Does this work? When I try this from frontend controller isLoggedIn returns false, I'm guessing it's because frontend has different session
    – Kazuki
    Apr 9, 2020 at 5:00
  • no current answer does not work Aug 3, 2022 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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