我已经完成了CakePHP3 Blog tutorial。现在我想阻止用户在同一台计算机上多次登录。我的意思是,在登录后,用户必须注销才能再次访问登录操作。我该怎么做呢?
发布于 2016-07-21 18:26:18
有完全相同的问题,下面是我如何解决它的。在AppController中,将以下代码添加到initialize函数中:
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
]);这基本上会迫使用户在做任何其他事情之前先登录。
在处理登录的控制器中,我添加了以下内容:
if($this->Auth->user()){
$this->Flash->error(__('You are already logged in!'));
return $this->redirect(['controller' => 'index']);
}这将检查是否已有用户登录,如果已经登录,则被重定向至主页。
发布于 2016-07-21 16:43:19
AuthComponent::identify()
您需要手动调用$this->Auth->identify()来使用request中提供的凭据来识别用户。然后使用$this->Auth->setUser()将用户登录,即将用户信息保存到会话中。对用户进行身份验证时,将按照附加身份验证对象的顺序对其进行检查。一旦其中一个对象可以识别用户,就不会检查任何其他对象。用于处理登录表单的示例登录函数可能如下所示:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'), [
'key' => 'auth'
]);
}
}
}上面的代码将首先尝试使用POST数据来识别用户。如果成功,我们设置会话的用户信息,使其在请求之间持续存在,然后重定向到他们正在访问的最后一个页面或在loginRedirect配置中指定的URL。如果登录不成功,则设置闪光消息。
请参阅此Authentication Session
https://stackoverflow.com/questions/38499022
复制相似问题