I am a little better than @ deep55.
The isAuthorized () method can throw an exception without problems, but I believe that inheriting the controllers will allow us to improve the authorization algorithm using the first AppController.isAuthorized (), and not the last.
So here is my solution, assuming that I am using a custom model called Utilisateur and a role model called Role.
AppController:
public function isAuthorized($user){ App::uses('Utilisateur','Model'); $User = new Utilisateur(); $isAdmin = $User->hasRole(10,$user['id']); if ($isAdmin) { return true; } } public function rejectRequest(){ $errorMessage = __("Sorry, you can't do this."); if ($this->isRest()) { throw new ForbiddenException($errorMessage); } else { $this->Auth->authError = $errorMessage; $this->Auth->flash['params']['class'] = 'alert-danger'; } return false ; }
Utilisateur Model:
public function hasRole($role_id, $user_id){ if (!isset($user_id)) { if (!empty($this->id)) { $user_id = $this->id ; } else throw new Exception("Error, parameter $user_id is missing", 1); } $user = $this->find('first',array( 'conditions' => array('Utilisateur.id' => $user_id), 'fields' => array('id'), 'contain' => array('Role.id') )); $roles = $user['Role']; foreach ($roles as $r) { if ($role_id == $r['id']) { return true; } } }
And last, in a specific controller:
public function isAuthorized($user){ if (parent::isAuthorized($user)) { return true; } if ( false ) { return true ; } if ( false ) { return true ; } return $this->rejectRequest() ; }
source share