CakePHP 2 - 手动登录不添加到会话

时间:2011-10-27 18:26:31

标签: php cakephp cakephp-2.0

我是CakePHP的新手并试图让我的头部注册/登录,我使用cakephp 2.0

如果我使用注册控制器功能创建用户,然后单独登录会话( $ 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.'));
        }
    }
}

Register.ctp查看

<?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-&gt; Auth-&gt;登录($ this-&gt; 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)){

2 个答案:

答案 0 :(得分:1)

尝试更改

if($this->Auth->login($this->data['User'])){

if($this->Auth->login()){

答案 1 :(得分:0)

我通过在PHP.ini中将“session.cookie_domain”的值更改为我的域名来解决此问题。

session.cookie_domain = my.domain.com

现在它完美无缺。

core.php的会话设置如下

Configure::write('Session', array(
    'defaults' => 'php'     
));
相关问题