CakePHP和用户登录功能

时间:2013-08-15 13:35:22

标签: php cakephp cakephp-2.1

这是一个简单的CakePHP登录功能(例子来自CakePHP食谱):

public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirectUrl());
        } else {
            $message = 'Username or password is incorrect';
            $this->Session->setFlash(__($message), 'default', array(), 'auth');
        }
    }
}

在测试此登录功能期间,我发现:

if ($this->Auth->login()) {
    // ...
}

即使先前已完成授权,它也允许用户登录。例如,如果我以 User1 身份登录而没有调用注销功能,我尝试以 User2 身份登录 - 我将收到下一个错误:

Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 83]

在这种情况下,我可以隐藏用户的登录表单。这是正确的方法吗?

更新:您对下一个代码段有什么看法:

public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->loggedIn()) {
            $this->Auth->logout();
        }
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirectUrl());
        } else {
            $message = 'Invalid login or password';
            $this->Session->setFlash(__($message), 'default', array(), 'auth');
        }
    }
}

2 个答案:

答案 0 :(得分:4)

食谱中的教程Simple Acl controlled Application - part 2建议您使用SessionComponent宣读数据。

您还可以使用AuthComponent检查用户是否已登录。在控制器中使用$this->Auth->user()。您还可以将键传递给第一个参数以获取users表的特定列,或跳过它以获取所有用户的信息。如果用户未登录或密钥不存在,则返回Null

您的登录方式可能如下所示(使用标有加号+SessionComponent的附加内容):

public function login() {
+   if ($this->Session->read('Auth.User')) {
+       $this->Session->setFlash('You are logged in!');
+       return $this->redirect($this->Auth->redirectUrl());
+   }
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirectUrl());
        } else {
            $message = 'Username or password is incorrect';
            $this->Session->setFlash(__($message), 'default', array(), 'auth');
        }
    }
}

答案 1 :(得分:0)

这可能是一个简单的修复 - 在您的登录控制器功能中,您可以检查是否设置了会话变量IsUserLoggedIn。如果不是,则设置它然后继续验证过程,否则,重定向到某个消息页面。

public function login() {
    if ($this->request->is('post')) {

        //check to see if user is logged in.
        if(isset($this->Session->read('IsUserLoggedIn'))) {
        ##perform redirection to "Already Logged In" message
        }

        if ($this->Auth->login()) {
            //write the IsLoggedIn variable to the session.
            $this->Session->write('IsUserLoggedIn', true);

            return $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Username or password is incorrect'), 'default',  array(), 'auth');
        }
    }
}

在注销时,删除此会话变量:

  $this->Session->delete('IsUserLoggedIn');

编辑:将会话写入移动到auth块内。