CakePHP 2.x无法阻止已删除和禁止的用户登录

hsw*_*ner 2 cakephp login cakephp-2.0 cakephp-2.1

我有一些代码可以防止已删除和被禁用的用户登录.要清除头脑,状态为-2意味着用户被删除,-1表示用户被禁止.下面是在本地工作正常的代码,但在现场它很糟糕.状态为-1或-2的用户仍然可以登录.我找不到问题所在.

if ($this->Auth->login()) {
    //first check if the user's status is -1 or -2. 
    $status = $this->Auth->user('status');

    if ($status == '-1') {
        $this->Auth->logout();
        $this->Session->setFlash(__('This account has been banned. Please contact with us.'));
        $this->redirect('/');
    } elseif ($status == '-2') {
        $this->Auth->logout();
        $this->Session->setFlash(__('This account has been deleted, and is not usable anymore.'));
        $this->redirect('/');
    }

    //something else
}
Run Code Online (Sandbox Code Playgroud)

Pre*_*ant 10

通过$this->Auth->login()检查您正在登录用户.

您可以避免这种情况,并在登录前检查用户信息,或者可以将状态标志添加到用户的范围.

$this->Auth->authenticate = array(
    AuthComponent::ALL => array(
        'userModel' => 'User',
        'scope' => array('User.status' => '> 0)
    ),
    'Form',
    'Basic'
);
Run Code Online (Sandbox Code Playgroud)

这会将status字段检查添加到登录过程.

如果要在示例中自定义消息,可以在处理登录之前检查用户信息的值:

$user = $this->User->findByUsername($this->data['User']['username']);
if (!empty($user)) {
    if ($user['User']['status'] == -1) {
        // Set message for banned account
    }
    if ($user['User']['status'] == -2) {
        // Set message for deleted account
    }
    $this->redirect( ... ); // Redirect away
}

if ($this->Auth->login()) {
    // Normal login process
}
Run Code Online (Sandbox Code Playgroud)

  • 范围键对CakePHP 2来说并不陌生. (2认同)