Monday, August 27, 2012

How to make CMS pages available only to logged in customers

Hello
Here is a possible solution on how to make cms mages available only to logged in customers.
Override the Mage_Cms_PageController. Here is a how to do it: http://www.extensionprogrammer.com/skin/frontend/default/dermodpro/pdf/magento-cheatsheet.pdf

Now add the following method in your new controller

public function preDispatch(){
		$restrictedIdentifiers = array('about-magento-demo-store');
		$pageId = $this->getRequest()
            ->getParam('page_id', $this->getRequest()->getParam('id', false));
        $page = Mage::getModel('cms/page')->load($pageId);
    	parent::preDispatch();
    	if (in_array($page->getIdentifier(), $restrictedIdentifiers)){
	    	if (!Mage::getSingleton('customer/session')->authenticate($this)) {
	            $this->setFlag('', 'no-dispatch', true);
	        }
    	}
    }
That's it. Enjoy. I know it's not 100% clean solution. If you want the clean solution, add a new field for the cms_page table (let's call it 'password_protect'), add the field in the admin form. After doing this the code above becomes:
public function preDispatch(){
		$pageId = $this->getRequest()
            ->getParam('page_id', $this->getRequest()->getParam('id', false));
        $page = Mage::getModel('cms/page')->load($pageId);
    	parent::preDispatch();
    	if ($page->getPasswordProtect()){
	    	if (!Mage::getSingleton('customer/session')->authenticate($this)) {
	            $this->setFlag('', 'no-dispatch', true);
	        }
    	}
    }
Marius.

4 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
    Replies
    1. The comment above was removed because it had a link in it. The comment was written by Brian Jones on Monday, February 11, 2013:
      "I think this kind of a blog must rank higher in the search engines. I also subscribed to your RSS feed."

      At the end there was a link that I removed.

      Delete
  2. Does this method also effect the home page (given that is also a CMS page) we have been looking for a solution to be able to password protect some (not all) cms pages for some time, and come up with pretty much nothing.

    What we ideally need is the ability to make certain CMS pages available to logged in users only, why this is not a standard feature of Magento i have no idea.

    ReplyDelete
    Replies
    1. It should work for homepage also. give it a try.

      Delete