3

I have a custom module in my magento (version 1.5) and it's meant to load the currently logged in admin username like this in one of my controller:

$current_user = Mage::getSingleton('admin/session')->getUser();
if ($current_user) {
    $this->current_user = $current_user->getUsername();
} else {
    $this->current_user = '';
}

When the code runs, $this->current_user is empty, so I did a var_dump($current_user); exit(); and it appears to be null akways (even if I am logged in).

Any ideas why this might be?

2
  • If you are logged in do you see in the admin on the top right near the serach "Logged in as USERNAME HERE"? The code that renders that section is the same as the one you use. And one more thing? are you running your code from a frontend area or backend area?
    – Marius
    Commented Oct 16, 2014 at 11:35
  • I am running the code from the front end area.
    – Latheesan
    Commented Oct 16, 2014 at 11:46

2 Answers 2

5

Based on the comments...
Magento does not share the admin and frontend sessions. even if you are logged in in the backend in one tab and you use the frontend on a different tab in the same browsers, the sessions are separated. Frontend does not know about the admin session and the admin session does not know about the frontend session.
So what you are trying to achieve is not really possible.
There are workarounds, but I would not recommend them.
fronend and backend should stay separate for security reasons.
But here you go:
This should work if you you store the sessions in the db: http://www.stackoverflow.com/a/16034942/2047249

3
Mage::getSingleton('core/session', array('name'=>'adminhtml'));
//verify if the user is logged in to the backend
if(Mage::getSingleton('admin/session')->isLoggedIn()){
  echo "Admin Logged in";
}
else
{
  echo "You need to be logged in as an admin.";
}
4
  • 1
    The first line Mage::getSingleton('core/session', array('name'=>'adminhtml')); solved my problem. I am trying to AJAX in admin but couldn't get the custom controller to load the admin session in preDispatch.
    – kiatng
    Commented Sep 10, 2015 at 1:36
  • The code to start the admin session is already in preDispatch natively so the first line is not needed. I found out that I just need to add form_key in the AJAX parameters to get the preDispatch working correctly and get the session going.
    – kiatng
    Commented Sep 10, 2015 at 2:04
  • This code is not working for me Commented Jul 10, 2017 at 6:54
  • This solved my problem. I also needed to use some custom ajax controllers in admin. The first line of your solution was needed so the admin session was loaded so I could verify whether an admin is actually logged in. Commented Feb 27, 2023 at 17: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.