Magento: Detect if admin is logged in in frontend pages

后端 未结 12 637
轻奢々
轻奢々 2021-02-04 00:09

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

12条回答
  •  旧时难觅i
    2021-02-04 00:53

    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):

          
       cache_lifetime
       cache_tags
       
    
    

    And this is the newsletterpopup's block class:

    And the phtml would be something like:

    canRender()): ?>
       // stuff
    
    

    Good luck!

提交回复
热议问题