0

我有几种方法UsersController,我正在尝试赋予角色明智的访问权限。如果

  1. user_types == 1(用户可以访问所有方法)
  2. user_types == 2(用户无法访问admin_list方法。
  3. user_types == 3(用户只能访问forget_password方法)

在控制器中,我尝试了以下代码

public $components = array('Session','RequestHandler','Auth'=>array(

            'loginRedirect' => array('controller' => 'users','action' => 'dashboard'),
            'logoutRedirect' => array('controller' => 'users','action' => 'login'),
            'authError'=>'You can not access this page!!',
            'authenticate' => array(
            'Form' => array(
                'fields' => array(
                  'username' => 'email', //Default is 'username' in the userModel
                  'password' => 'password'  //Default is 'password' in the userModel
                )
              ),
            ),
            'authorize' => array('Controller')
        ));

        public function isAuthorized($user) {
            return true;
        }

在我允许的过滤器之前

    $this->Auth->allow('login','logout');

现在UserController我尝试了下面的代码

public function isAuthorized($user) {
    // Admin can access every action
    if (isset($user['usertype_id']) && $user['usertype_id'] == 1) {
            return true;
    }
    else if(isset($user['usertype_id']) && $user['usertype_id'] == 2)
    {
         $this->Auth->deny('admin_list');
    }else
        $this->Auth->allow('change_password');

    return parent::isAuthorized($user);
    }

问题是它总是返回 true。如果我使用 user_type = 3 登录,我可以访问所有方法。

4

1 回答 1

1

Auth::allow()并且Auth::deny()旨在定义允许未登录用户访问哪些操作(身份验证),并且不用于授权

为此,您必须isAuthorized()像您所做的那样在控制器中进行定义。但是,此方法预计会返回true(登录的用户/组被授权访问操作)或false(授权被拒绝)。

您的UsersController::isAuthorized()方法应重写为:

public function isAuthorized($user) {

    if (!isset($user['usertype_id'])) {
        return false;
    }

    if($user['usertype_id'] == 2 && $this->action=='admin_list') {
       return false;           
    }

    if($user['usertype_id'] == 3) && $this->action!='forget_password'){
        return false;
    }

    return true;
}

有关ControllerAuthorize的更多信息,请参阅 Cookbook 。

于 2015-12-13T09:11:31.247 回答