Quickly grant Auth access to multiple controllers

Common way to allow Auth access to all actions in a controller is to do something like this:

//In some controller

public function beforeFilter() {
  $this->Auth->allow('*');
  parent::beforeFilter();
}

However it can get pretty tedious if you’ve got lots of controllers and have to go through a bunch of them to enable (or disable) access.

Instead, try something like this in your AppController:

public function beforeFilter() {
  $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
  $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
  $this->allowAccess();
}

private function allowAccess() {
  if(in_array($this->name, array('Pages'))) {
    $this->Auth->allow('*');
  }
}

The above will let Auth to access everything in the PagesController.
If you need to grant access to additional controllers simply add them to the array of names:
array(‘Pages’, ‘Books’, ‘Customers’, ‘Etc’)

Having to deal with a single file to grant/deny access just makes things easier…
You could even make that “grantable” array a property of the AppController.

Related Posts

%d bloggers like this: