我有一个表,用于拆分链接到用户表(user_level_id)的用户(user_levels)。级别5是管理员。

我想限制某些 Action 不会被查看,并且我可以使用isAuthorized做到这一点。我按照书去了,我敢肯定我做对了,但是没有用。尽管我在isAuthorized中拒绝了它,但它允许任何登录的用户仍然可以访问任何操作。

这是我的代码:

 App Controller:public $components = array(
    'Session',

    'Auth' => array(
        'loginAction' => array(
            'controller' => 'users',
            'action' => 'login',
        ),
        'authError' => "Your username and password is incorrect, please try again.",
        'authenticate' => array(
            'Form' => array(
                'scope' => array('User.user_status_id' => 1)
            )
        ),
        'redirect' => array("controller" => "users", "action" => "profile"),
        'loginRedirect' => array("controller" => "users", "action" => "profile")
    )
);

public function isAuthorized($user = null) {
    if($this->Auth->user("user_level_id") == 5) {
        return true;
    }
    // Default deny
    return false;
}

public function beforeFilter() {
    $this->Auth->allow("display");
   if($this->Auth->loggedIn() == true) {
       $this->set("user_name",$this->Auth->user("first_name")." ".$this->Auth->user("last_name"));
       $this->set("loggedIn",true);
       if($this->Auth->user("user_type_id") == 5) {
           $this->set("navigation","navigation_admin");
       } else {
           $this->set("navigation","navigation_loggedin");
       }
   } else {
       $this->set("loggedIn",false);
       $this->set("navigation","navigation_notloggedin");
   }

}

 }

 // Users Controller:

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

public function isAuthorized($user = null) {
    if($this->Auth->user("user_level_id") == 5) {

        return true;
    }
    // Default deny
    return parent::isAuthorized($user);
}

最佳答案

看起来您只是缺少配置而只告诉AuthComponent使用isAuthorized()

'Auth' => array(
        'loginAction' => array(
            'controller' => 'users',
            'action' => 'login',
        ),
        'authError' => "Your username and password is incorrect, please try again.",
        'authenticate' => array(
            'Form' => array(
                'scope' => array('User.user_status_id' => 1)
            )
        ),
        'authorize' => array('Controller'), // <- here
        'redirect' => array("controller" => "users", "action" => "profile"),
        'loginRedirect' => array("controller" => "users", "action" => "profile")
    )

10-08 19:23