2

在我的 Cake 应用程序中,我正在执行基本身份验证。我更喜欢保持简单和语义化(不喜欢 ACL),所以我只是检查用户的角色,并相应地允许或拒绝。

现在,授权所有功能都按预期进行,但我遇到了一个奇怪的问题,无论用户是否尝试允许的操作,都会显示 Auth 错误消息。在他们注销后它仍然可见。

这是应用控制器:

public $components = array(
    'Session',
    'Password',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
        'authError' => "Sorry, you're not allowed to do that.",
        'authorize' => array('Controller')
    ),
    'RequestHandler'
);

public function beforeFilter() {
    $this->set('loggedIn', $this->Auth->loggedIn());
    $this->set('current_user', $this->Auth->user());
    $this->set('admin', $this->_isAdmin());
    $this->set('coach', $this->_isCoach());
    $this->Auth->allow('login', 'logout', 'display');
}

public function isAuthorized($user) {
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }
    return false;
}

来自另一个控制器的 beforeFilter 和 isAuthorized:

public function beforeFilter() {
    parent::beforeFilter();
}

public function isAuthorized($user) {
    if ($user['role'] === 'coach') {
        if ($this->action === 'index') {
            return true;
        }
        if (in_array($this->action, array('view', 'edit', 'delete'))) {
            $id = $this->request->params['pass'][0];
            $this->User->id = $id;
            if ($this->User->field('client_id') === $user['client_id'] ) 
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
    return parent::isAuthorized($user);
}
4

1 回答 1

1

我决定在我的用户控制器中执行此操作,并且一切似乎都运行良好,而且它更干净/更具可读性:

public function isAuthorized($user = null) {
    switch($this->action) {
        case "index":
        case "add":
            if ($user['role'] == 'coach') {
                return true;
            }
            break;

        case "view":
        case "edit":
        case "delete":
            $id = $this->request->params['pass'][0];
            $this->User->id = $id;
            if ($user['role'] == 'coach' && $this->User->field('client_id') == $user['client_id']) {
                return true;
            }
            break;
    }
    return parent::isAuthorized($user);
}
于 2012-04-05T21:32:33.323 回答