CakePHP和用户登录功能


CakePHP and User login function

这里有一个简单的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');
        }
    }
}

教程Simple Acl控制的应用程序-食谱中的第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');
        }
    }
}

这可能是一个简单的修复方法-在登录控制器函数中,您可以检查是否设置了会话变量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');

EDIT:已将会话写入移动到身份验证块内部。