根据用户在 cakephp 中的角色允许多个控制器给用户

Allow multiple controllers to users according to their role in cakephp

假设,有两个角色:一个是admin,另一个是restaurant_owner

我想授予restaurant_owner一些页面的访问权限。

AppController中,我使用了beforeFilter函数。这是代码..

public function beforeFilter() {
   if($this->Auth->user('role') == 'restaurant_owner'){
     /* Controllers Name, that Admin want to give access to restaurant admin*/
      $this->loadModel('Userpermission');
      $AuthPermission = $this->Userpermission->find('first',array('conditions' => array('Userpermission.user_id' => $this->Auth->user('id'))));
      print_r($AuthPermission); //returns controller names e.g. receipes, menuitems
  }
}

我的问题是,我如何拒绝除少数之外的所有控制器访问角色 restaurant_owner?我正在使用 CakePHP 2.x.

处理此问题的正确方法是通过 ControllerAuthorizeAuthComponent::isAuthorized() 回调。

首先,您必须在 AppController 中启用此功能。编辑您的 Auth 配置和数组并添加以下内容:

public $components = array(
    'Auth' => array('authorize' => 'Controller'),
);

然后将以下内容添加到 restaurant_owner 应该有权访问的控制器中:

public function isAuthorized($user) {

    if ($user['role']=="restaurant_owner") {
        return true;
    }

    return parent::isAuthorized($user);
}

最后,将以下内容添加到 AppController

public function isAuthorized($user) {

    if ($user['role']=="restaurant_owner") {
        return false;
    }

    return true; //Every other role is authorized
}

您必须调整上述逻辑以满足您的需要。