In my Cake app, I'm doing a basic authentication. I prefer to keep it simple and semantic (don't like ACL) so I'm simply checking a user's role, and allowing or denying accordingly.
Now, the authorization all functions as expected, but I'm getting a weird issue where the Auth error message shows regardless of whether the user attempts an allowed action or not. It remains visible after they've logged out.
Here's the AppController:
public $components = array(
'Session',
'Password',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
'authError' => "Sorry, you're not allowed to do that.",
'authorize' => array('Controller')
),
'RequestHandler'
);
public function beforeFilter() {
$this->set('loggedIn', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
$this->set('admin', $this->_isAdmin());
$this->set('coach', $this->_isCoach());
$this->Auth->allow('login', 'logout', 'display');
}
public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
return false;
}
The beforeFilter and isAuthorized from another controller:
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user) {
if ($user['role'] === 'coach') {
if ($this->action === 'index') {
return true;
}
if (in_array($this->action, array('view', 'edit', 'delete'))) {
$id = $this->request->params['pass'][0];
$this->User->id = $id;
if ($this->User->field('client_id') === $user['client_id'] )
return true;
} else {
return false;
}
}
return false;
}
return parent::isAuthorized($user);
}
I decided to do this in my Users controller instead, and all seems to be working well, plus it's cleaner/more readable:
public function isAuthorized($user = null) {
switch($this->action) {
case "index":
case "add":
if ($user['role'] == 'coach') {
return true;
}
break;
case "view":
case "edit":
case "delete":
$id = $this->request->params['pass'][0];
$this->User->id = $id;
if ($user['role'] == 'coach' && $this->User->field('client_id') == $user['client_id']) {
return true;
}
break;
}
return parent::isAuthorized($user);
}