如果用户在登录表单上输入凭据,我就可以登录用户。如果我尝试手动登录,我无法登录用户。真的很奇怪。
使用表单登录的代码[这很好用]:
public function login() {
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect('/cars');
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
手动登录代码[这不起作用]:
public function loginManually()
{
try {
$user = $this->Users->find()
->where(['username' => 'abc@xyz.com'])
->contain(['Profiles'])
->firstOrFail();
$this->Auth->setUser($user->toArray());
return $this->redirect('/cars');
} catch (\Exception $ex) {
Log::write('error', $ex);
$this->Flash->error(__('An error occurred Please try again'));
}
return $this->redirect('/login');
}
经过调试 - 代码可以正常工作$this-Auth->setUser($user->toArray());
- 但是当我将其重定向到/cars
时,系统会返回一个错误,指出用户没有登录。我感到困惑 - 任何帮助都表示赞赏
答案 0 :(得分:0)
而不是电子邮件通过主键(id)获取用户记录。 这对我有用
$user = $this->Modelname->get($id);
$this->Auth->setUser($user->toArray());
debug($this->Auth->user());