Magento: Detect if admin is logged in in frontend pages
Asked Answered
J

12

25

I have created a magento extension. I want to implement access to the extension. The extension creates a page in frontend and i want only admin to access that page. So basically i need something that would detect that if admin is logged in in frontend pages.

I have tried several solution but noting seem to work .

if(Mage::getSingleton('admin/session', array('name' => 'adminhtml'))->isLoggedIn()) echo 'logged in'; else echo 'not logged in';

Check on frontend if admin is logged in

Mage::getSingleton('core/session', array('name'=>'adminhtml'));
$adminSession = Mage::getSingleton('admin/session');
$adminSession->start();
if ($adminSession->isLoggedIn()) {
   echo 'logged in';
}
Jariah answered 5/4, 2013 at 10:5 Comment(0)
A
14

The above solutions doesn't work!

Here is a solution that works ( its not that clean ! but this will work anywhere in your application in phtml view or model or controller or helper ! )

$sesId = isset($_COOKIE['adminhtml']) ? $_COOKIE['adminhtml'] : false ;
$session = false;
if($sesId){
    $session = Mage::getSingleton('core/resource_session')->read($sesId);
}
$loggedIn = false;
if($session)
{
    if(stristr($session,'Mage_Admin_Model_User'))
    {
        $loggedIn = true;
    }
}
var_dump($loggedIn);// this will be true if admin logged in and false if not
Ardelia answered 16/4, 2013 at 10:39 Comment(8)
Weird, doesn't work for me at all, reports false no matter what (v 1.7.0.2)Eleonoreeleoptene
Null, but I discovered it's an issue with admin session not being available when on a frontend page (I was trying to run this on a CMS page)Eleonoreeleoptene
if you its equal null this means you dont have adminhtml session ! try to login i have tested on 1.7 and 1.6 and its working no issuesArdelia
This will only work with DB based sessions, not for file based sessions (PHP default) or other session backends like memcache.Dixson
It's better to use session_decode($session); if(Mage::getSingleton('admin/session')->isLoggedIn()) ... rather than if(stristr($session,'Mage_Admin_Model_User'))... . That way you're actually decoding the session info rather than relying on a string that might be injected into session data.Loreeloreen
How to get all logged in admin users from magento?Etz
I don't think there is direct way to do this. but you can look at events logs in magento database , you will find entity related to users and then you find the event logged in and didn't logout and compare it with cookie lifetime ..Ardelia
These solutions only work when the frontend store's domain matches the admin domain (technically, if they're on the same origin). If you have a multisite installation that uses different domains for some stores, they won't see the admin cookie and you will need some different workaround.Ettore
A
7

Christoph Peters posted a link which solved my problem (Detect if admin is logged in in frontend pages):

//check if adminhtml cookie is set
if(array_key_exists('adminhtml', $_COOKIE)){
   //get session path and add dir seperator and content field of cookie as data name with magento "sess_" prefix
   $sessionFilePath = Mage::getBaseDir('session').DS.'sess_'.$_COOKIE['adminhtml'];
   //write content of file in var
   $sessionFile = file_get_contents($sessionFilePath);

   //save old session
   $oldSession = $_SESSION;
   //decode adminhtml session
   session_decode($sessionFile);
   //save session data from $_SESSION
   $adminSessionData = $_SESSION;
   //set old session back to current session
   $_SESSION = $oldSession;

   if(array_key_exists('user', $adminSessionData['admin'])){
      //save Mage_Admin_Model_User object in var
      $adminUserObj = $adminSessionData['admin']['user'];
      echo 'ADMIN USER IS LOGGED IN';
   }
   else
   {
      echo 'ADMIN USER IS NOT LOGGED IN'
   }
}

Thank you very much Christoph Peters!

Amoroso answered 2/9, 2014 at 14:13 Comment(1)
I have tried so many versions of this code and this is the only one that worked for me. No idea why any of the others didn't but happy I've now got it going. Thank you very much Christoph Peters, indeed!Perri
S
7

there is a new magento module, written by alan storm: https://github.com/astorm/Magento_CrossAreaSessions

$adminhtml  = Mage::getModel('pulsestorm_crossareasession/manager')->getSessionData('adminhtml');

$adminUser = $dataAdminhtml['admin']['user'];
$loggedIn = $adminUser->getId() && $adminUser->getIsActive();
Splashboard answered 23/10, 2014 at 1:26 Comment(1)
This solution works fine, but if there's no backenduser is logged in, it runs into an error, because $adminUser is null and you try to getId() on null. I'd suggest to check if ($adminUser) before setting $loggedIn, otherwise default to false.Zest
Q
3

If you're trying to make it work within the template / phtml files, and/or inside the Block's class you're going to have a hard time. Mainly because magento (aggressively) caches your PHTML blocks for performance purposes thus undoing any program flow control statements you have especially stuff related with cookie checking. I have no direct / lengthy / indepth explanation why but that's just how I've encountered it over and over again.

However, your solution should be correct, but you need to do the check within a controller's preDispatch method like so to avoid the aformentioned aggressive caches since controllers are never cached. (shown in Nick's solution in the question that you linked.):

// Ensure we're in the admin session namespace for checking the admin user..
Mage::getSingleton('core/session', array('name' => 'adminhtml'))->start();

$admin_logged_in = Mage::getSingleton('admin/session', array('name' => 'adminhtml'))->isLoggedIn();

// ..get back to the original.
Mage::getSingleton('core/session', array('name' => $this->_sessionNamespace))->start();

IF you really do need to perform the above checks inside PHTML files or named blocks, check out the following code on how to turn off block-level caching and possibly make it work. What I did before was disable caching for the footer block (in which the child block, not phtml, contains code to check
for a specific cookie)

First off, the block call (found in your local.xml, or module layout update xml, or anywhere you can do layout updates, really. I prefer breaking up my customizations into modules so definitely module layout update xml is the way to go):

<reference name="footer">      
   <action method="unsetData"><key>cache_lifetime</key></action>
   <action method="unsetData"><key>cache_tags</key></action>
   <block type="newsletterpopup/popup" name="newsletterpopup_footer" template="newsletterpopup/popup.phtml"/>
</reference>

And this is the newsletterpopup's block class:

<?php
class Launchpad_Newsletterpopup_Block_Popup extends Mage_Core_Block_Template {
    public function canRender() {
         // Check if cookie exists here       
    }
    public function afterRender() { // if block has rendered, this is called.
        // Set cookie, if it doesn't exist here.
    }
}

And the phtml would be something like:

<?php if($this->canRender()): ?>
   // stuff
<?php endif; ?>

Good luck!

Quartana answered 14/4, 2013 at 13:37 Comment(0)
S
3

Here is a solution this works with Magento 1.7.0.2 (tested) and on each frontend site, I use this in an controller not extending from Mage_Adminhtml_Controller_Action.

https://peters-christoph.de/tutorials/magento-pruefe-admin-session-logi-im-frontend/

Seaden answered 30/8, 2013 at 19:21 Comment(3)
from all of the solution posted here, these is one which is working.. used in fronAction controllerArdeen
This is the only solution here that worked for me. I had a need to test in a .phtml file and yeps, logged in and out of the admin and it response correctly.Bekha
Yes, this saved me in a crunch today... Thanks so much. Here's a condensed version: if(array_key_exists('adminhtml', $_COOKIE)){ $sessionFilePath = Mage::getBaseDir('session').DS.'sess_'.$_COOKIE['adminhtml']; $sessionFile = file_get_contents($sessionFilePath); $oldSession = $_SESSION; session_decode($sessionFile); $adminSessionData = $_SESSION; $_SESSION = $oldSession; } if(array_key_exists('user', $adminSessionData['admin'])){ $adminUserObj = $adminSessionData['admin']['user']; } if ($adminUserObj) { // var_dump($adminUserObj); } else { header("Location: /"); die(); }Traitorous
S
1

This code will works

//get the admin session
Mage::getSingleton('core/session', array('name'=>'adminhtml'));

//verify if the user is logged in to the backend
if(Mage::getSingleton('admin/session')->isLoggedIn()) {
  //do stuff
}
else
{
  echo "404 page not found";
}

OR

$adminsession = Mage::getSingleton('admin/session', array('name'=>'adminhtml'));

if($adminsession->isLoggedIn()) {
    //do stuff
} else {
    echo "404 page not found";
}

Did you try to dump the $_SESSION variable? Maybe it will help you get on the right track.

Sheerness answered 17/4, 2013 at 9:50 Comment(9)
No man this doesn't work. Neither in controller,model or block.Jariah
@NirmalRam it will work, because here it is working, which version of magento you are using?Sheerness
I am using community 1.7. And it doesn't work. Let me explain you. I have created an extension and that extends frontend controller and its displayed in frontend. I just want that to be accessible by admin.Jariah
@NirmalRam yes my posted code will work, because I have already developed that type of modules which is only accessible by admin. did you try var_dumping the $_SESSION variable?Sheerness
what session value you got?Sheerness
If you check i have already stated that the answer you posted doesn't work. So please try what have you written in a frontend controller which extends Mage_Core_Controller_Front_ActionJariah
ohh.. you didn't get me.. I am saying you that which session value you are getting while var_dumping the $_SESSION variable?.... did you get any values or not??Sheerness
That's very long and i can't paste here. What do you expect me to get?Jariah
Looks nice and clean code; but pathetic it does not work.Prussia
S
1

Apart from trying to pull session id from adminhtml cookie, which may or may not work IMHO is better just to "skin" page you need to show to look like its in frontend and use admin controller so it will run under admin session.

Another solution is to "copy" customer from admin to frontend and log them in before hitting your page and then its the matter of just checking if logged in customer is member of some group.

Shaving answered 18/4, 2013 at 14:6 Comment(1)
Thanks i have already done this as a temporary solution. But i need my extension to be accessible by admin only and it would be in frontend.Jariah
S
1

It is quite simple but not a recommended solution. I myself spend number of hours to do this. For, windows based server try below solution:

$sessionFilePath = Mage::getBaseDir('session').DS.'sess_'.$_COOKIE['adminhtml'];
$sessionFile     = file_get_contents($sessionFilePath); 
$exp_cookie   = explode(';',$sessionFile);
if(count($exp_cookie)   >   100)
{
  return "login";
}
return "expire";    

For, Linux based server try below solution:

$sessionFilePath = Mage::getBaseDir('session').DS.'sess_'.$_COOKIE['adminhtml'];
$sessionFile     = file_get_contents($sessionFilePath); 
$exp_cookie   = explode('--',$sessionFile)
if(count($exp_cookie)   >   10)
{
  return "login";
}
return "expire";

Thanks, Kashif

Stepper answered 3/2, 2014 at 11:45 Comment(0)
S
0

The key to be able to use:

// Ensure we're in the admin session namespace for checking the admin user..
Mage::getSingleton('core/session', array('name' => 'adminhtml'))->start();

$admin_logged_in = Mage::getSingleton('admin/session', array('name' => 'adminhtml'))->isLoggedIn();

// ..get back to the original.
Mage::getSingleton('core/session', array('name' => $this->_sessionNamespace))->start();

is that the controller must extends Mage_Adminhtml_Controller_Action

than you can use this code in the preDispatch function.

And setup the routers for this controller in the admin section of your config.xml.

Slacken answered 14/4, 2013 at 17:28 Comment(2)
If the controller would extend Mage_Adminhtml_Controller_Action then why would i ask this question. Thanks but my controller extends frontend controller and if i would extend it by adminhtml then it would redirect to backend.Jariah
You can setup route in a way that the page looks like it is in the frontend (no /admin) and extend Mage_Adminhtml_Controller_Action. Well, I got it working that way for me.Slacken
Z
0
require_once $dir.'app/Mage.php';
umask(0);

$apps = Mage::app('default');
Mage ::getSingleton('core/session', array('name'=>'adminhtml'));
$adminSession = Mage::getSingleton('admin/session');
$adminSession->start();
if ($adminSession->isLoggedIn()) {
   //echo "logged in";
} 
 else { 
      //echo "Not logged in";
      exit();
 }?> 
Zingaro answered 3/11, 2013 at 21:29 Comment(0)
S
-1

Check this blog, I think you need not check with start() before checking with isLoggedIn().

Mage::getSingleton('core/session', array('name'=>'adminhtml')); // get sessions

$check = Mage::getSingleton('admin/session', array('name'=>'adminhtml')); //get admin sessions

    if($check->isLoggedIn()) { //check is admin logged in
        echo "Admin is logged in";
    } else {
        echo "Admin is offline";
    }
Selfpossession answered 5/4, 2013 at 10:16 Comment(2)
Your module's adminhtml controller should extend from Mage_Adminhtml_Controller_Action. Else you cant check if admin is logged in.Selfpossession
No its not like that. I can check.You should try Meabed's answer. It works actually. Just need to test more.Jariah
B
-1

If you are using cm redis session try this: (worked for me)

$sesId = isset($_COOKIE['adminhtml']) ? $_COOKIE['adminhtml'] : false ;
if($sesId){
    $session = Mage::getSingleton('core_mysql4/session')->read($sesId);
}
$loggedIn = false;
if($session)
{
    if(stristr($session,'Mage_Admin_Model_User'))
    {
        $loggedIn = true;
    }
}

var_dump($loggedIn);

because if you are using cm redis its rewrites db session module with its own model.

Bouzoun answered 5/2, 2018 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.