cakepp被授权检查其他控制器的内部操作


cakephp isauthorized check inside other controller action

假设我的控制器中有一个函数isAuthorized(),它检查用户是否有权执行控制器操作addedit。现在假设我在一个控制器动作my_custom_action中。我如何检查我的用户是否有权通过使用类似的东西在我的控制器动作my_custom_action内执行动作addedit

$this->Auth->isAuthorized();

感谢

在app_controller中,我创建了这个(类)函数。首先我检查正在使用的控制器,然后我检查控制器的操作。你也可以看看这篇"基于简单模型的访问控制"烘焙文章。

function isAuthorized() {
    switch($this->name) {
        case 'Everyone': /* EveryoneController */
            return true;
            break;
        case 'Banned': /* BannedController */
            $this->Auth->authError = __('You do not have permission to ', true).$this->action.' '.strtolower($this->name);
            return false;
            break;
        default:
            switch($this->action) {
                case 'index':
                    return true;
                    break;
                case 'add':
                case 'edit':
                case 'delete':
                    if (/* permission check */) {
                        return true;
                    } else {
                        $this->Auth->authError = __('You do not have permission to ', true).$this->action.' '.strtolower($this->name);
                        return false;
                    }
                    break;
                default:
                    return true;
                    break;
            }
            break;
    }
}

这会检查请求"my_custom_action"的当前用户是否是管理员,如果是,则授予访问权限。

public function isAuthorized($user) {
        if (in_array($this->action, array('my_custom_action'))) {
             if ($this->Auth->user('is_admin')) 
                return true; 
             else 
                return false;
        }
}