php - CakePHP 2 - 手动登录不添加到 session

标签 php cakephp cakephp-2.0

我是 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/

相关文章:

html - CakePHP 3.7.1 将类添加到表单选择控件选项

除了 session 之外的 cakephp redis 存储

php - 将值从 MySql 传递到 PHP。如何避免NULL值

php - 你如何在 PHP 中格式化 DOM 结构?

php - 如何获取国外网址(例如 facebook 或 twitter)的缩略图/图像和描述?

php - Apache 在运行 Controller 的索引页时崩溃

php - 处理文件请求和可用性

cakephp - 如何在 CakePHP 中编写跨多个表的联接查询?

php - 从 View 中获取当前用户

CakePHP 插件 CSS