Search code examples
aclcakephp-2.2

Block access to pages in cakePHP


How do I block access to any page in cakePHP. With page, I'm referring to actual views lying in the Page folder.

When I remove this line in, it works, but it also stops users from logging in. It would create a direct loop:

$this->Auth->allow('display');

Basically, when a user wants to view any page, and they are not logged in, they will be redirected to the login (app/users/login) page. After they've logged in, they will be directed to the page they last tried to access.

How would I go about this?


Solution

  • The problem in your situation is that all pages shown by the pagesController are the same action (display()), only using a different parameter (the page to display). You can therefore not block access to the display action, because that will block access to all pages.

    If the number of pages is limited, then the easiest way to implement this is ControllerAuthorize. Read the documentation here; Using ControllerAuthorize

    class AppController extends Controller {
        public $components = array(
            'Auth' => array('authorize' => 'Controller'),
        );
        public function isAuthorized($user = null) {
            // Make all actions public 
            return true;
        }
    }
    

    Then, inside your pages controller;

    class PagesController extends AppController {
    
        public function isAuthorized($user = null) {
            if ('display' !== $this->request->action) {
                // other actions; let he AppController handle access
                return parent::isAuthorized($user);
            }
    
            if (!empty($user)) {
                // Logged-in users have access to any page
                return true;
            }
    
            $page = empty($this->request->params['pass'][0]) ? null : $this->request->params['pass'][0];
    
            switch($page) {
                case 'home':
                case 'about':
                // etc
                   return true;
            }
    
            // all other pages are 'private'
            return false;
        }
    }
    

    Just an example, of course, modify to fit your needs