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!

Kevin Chavez
  • 890
  • 2
  • 13
  • 33
Ramesh
  • 986
  • 1
  • 14
  • 38

3 Answers3

3

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-&gt;authSession = $authSession;
    $this-&gt;state = $state;
    $this-&gt;getActiveAdmin = $getActiveAdmin;
    $this-&gt;userFactory = $userFactory;
    $this-&gt;registry = $registry;
    $this-&gt;request = $request;
}

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

public function execute()
{
    $activeUserData = $this-&gt;getActiveAdmin-&gt;create()-&gt;getCollection();
    $activeUserData-&gt;addFieldToFilter('status', '1');
    foreach ($activeUserData as $activeUserKey =&gt; $activeUserVal) {
        $checkoutTime = intval($activeUserVal-&gt;getCheckoutTime() - 1);
        if ($checkoutTime &lt;= 0) {
            $activeUserVal-&gt;setCheckoutTime('0');
            $activeUserVal-&gt;setStatus('0');
        } else {
            $activeUserVal-&gt;setCheckoutTime($checkoutTime);
        }
        $activeUserVal-&gt;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-&gt;registry = $registry;
    parent::__construct($context, $data);
}

public function getActiveAdmin()
{
    return $this-&gt;registry-&gt;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-&gt;registry = $registry;
}

public function getActiveAdmin()
{
    return $this-&gt;registry-&gt;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

Msquare
  • 9,063
  • 7
  • 25
  • 63
  • 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()]

    – Kevin Chavez Aug 08 '22 at 06: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 08 '22 at 06:43
  • @KevinChavez you can also add your data into https://nimb.ws/vh6ayo array and get them using Registry. Data must be store into our table. – Msquare Aug 08 '22 at 06: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.

Sumit
  • 4,875
  • 2
  • 19
  • 35
Abhishek Panchal
  • 4,948
  • 3
  • 21
  • 38