CakePHP Auth组件在登录前检查用户

时间:2010-08-25 09:49:06

标签: cakephp login components authentication verify

我希望阻止被禁止的用户登录该网站并向他们发送禁止他们的消息。我尝试使用isAuthorized(),但它允许用户登录,并且只有在此之后才会拒绝他对未经授权的操作的许可。

所以,基本上我想知道在登录过程发生之前将检查用户表是否为banned = true的条件放在哪里。现在我的登录功能是空的,因为它由Auth组件自动控制。

5 个答案:

答案 0 :(得分:12)

最后,我通过API找到了解决方案。我想知道是否有人曾经使用过这个,因为没有人指出我,或者我可能不够清楚。无论如何,要为登录过程添加条件,您只需将其放入变量$ this-> Auth-> userScope

因此,要检查用户是否被禁止,我只是将此行添加到AppController中的beforeFilter(),

$this->Auth->userScope = array('User.banned'=>0);

希望这有助于某人。

答案 1 :(得分:6)

或者: $this->Auth->userScope = array('User.banned'=>0);

包含Auth组件时可以执行此操作。这可能会节省一些微小的开销,因为每次解析控制器时都不会调用$this->Auth->userScope

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'passwordHasher' => 'Blowfish',
                'scope' => array('User.banned' => 0)
            )
        ),
        'authorize' => array('Controller')
    )
);

答案 2 :(得分:3)

如果您已经启动并运行整个Auth系统,为什么不按照KISS原则撤销密码或更改用户名?如果他们不能再像以前那样能够对您的系统进行身份验证,那么他们应该能够推断出他们被禁止了。

如果这还不够,那么另外你可以添加下面的代码。

function login() {
  if ($this->Session->read('Auth.User')) {
    $this->Session->setFlash('You are alreadylogged in!~~~~~~~~~~~');   
  }
  $this->Session->setFlash('You have been banned!');    
  $this->redirect(array('controller'=>'users','action'=>'index'));
}

编辑1:对于您在评论中指出的更动态的方法,您可以检查UsersController::beforeFilter()中所关注的用户记录的is_banned列,并相应地设置您的Flash消息。同时根据$this->Session->read('Auth.User.is_banned')的结果进行重定向。也许你想在攻击你的问题之前查看<?php debug $this->Session->read('Auth.User) ?>的输出。

编辑2:我的错。您可以通过$this->Session->write(...)将is_banned存储在会话中的某个位置。阅读is_banned = true后,您可以将用户注销。

答案 3 :(得分:2)

你必须使用:

/** Function is executed after the login*/
function isAuthorized() {
return true;
}

您可以检查用户是否被禁止。即。

/** Function is executed after the login*/
function isAuthorized() {
if($this->Auth->user('banned') == 1){ //column banned should be in the users table
       $this->Session->setFlash('You have been banned!');    
       return false;
    }
    return true;
}

我相信这是正确的方法。

答案 4 :(得分:1)

在阅读了关于Nik方式的最新评论后,我认为您可以通过在代码中的适当位置通过$ this-&gt; Auth-&gt; logout()手动注销用户来优化原始解决方案(按照通过重定向)。这样看起来他/她从未登录过。

相关问题