CakePHP:Auth错误,即使允许操作也是如此

时间:2012-04-05 19:28:40

标签: cakephp authentication

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

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

这是AppController:

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);
}

1 个答案:

答案 0 :(得分: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);
}