我是 CakePHP 的新手,正在尝试注册/登录,我使用的是 cakephp 2.0
如果我使用注册 Controller 函数创建用户,然后单独登录 session ($this-Auth-user()) 包含我期望的所有模型值。
如果我遵循 cakephp 2.0 书籍示例并在注册期间手动登录,那么我会登录但$this->Auth->user() 仅包含注册表单中的字段不是用户模型。 (即它缺少我的模型字段“创建”、“全名”等,但包括未加密的“密码”和“密码确认”)
我是不是漏掉了什么?
登录操作:
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid Username or Password.'), 'default', array(), 'auth');
}
}
}
注册操作(自动登录):
public function register(){
if($this->request->is('post')){
$this->User->create();
if($this->User->save($this->request->data)){
//Login automatically
if($this->Auth->login($this->data['User'])){
$this->Session->setFlash(__('Welcome to Test Site.'), 'default', array(), 'auth');
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Failed to login with new account.'), 'default', array(), 'auth');
$this->redirect(array('action' => 'login'));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
注册.ctp View
<?php
echo $this->Form->create('User', array('action' => 'register'));
echo $this->Form->input('username');
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->input('passwordconfirm', array('label' => 'Confirm Password', 'type' => 'password'));
echo $this->Form->input('email', array('label' => 'Email (optional)'));
echo $this->Form->end('Join');
?>
为任何帮助干杯,抱歉这有点长!
编辑:
找到解决方法! 看起来 $this->Auth->login($this->data['User']) 无法对我的用户进行 AuthComponent::identify() 所以我将其更改为以下 3 行:
$LoggedInID = $this->User->field('id', array('username' => $this->Auth->user('username')));
$user = $this->User->read(null, $LoggedInID);
$this->Auth->login($user);
这是一种享受。
编辑:您也可以只使用 save() 的返回值:
if($user = $this->User->save($this->request->data)){
//Login automatically
if($this->Auth->login($user)){
最佳答案
尝试改变
if($this->Auth->login($this->data['User'])){
到
if($this->Auth->login()){
关于php - CakePHP 2 - 手动登录不添加到 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7920532/