我正在研究我们新项目的用户管理组件。 计划是:
- 用户使用最少量的帐户数据(用户名、密码、电子邮件)在页面上注册
- 用户会收到一封电子邮件,其中包含用于激活帐户的激活链接
- 用户点击链接并激活其帐户
- 系统在激活后自动登录用户,并将其重定向到包含帐户信息(上次登录、“用户名”等)的仪表板
但是自动登录存在一些问题。这是我使用的代码的一部分:
<?php
...
// set userstatus to "active" and delete meta information "activation_key"
// then automatically login
$this->User->id = $id;
$this->User->saveField('modified', date('Y-m-d H:i:s') );
$this->User->saveField('status', 1 );
// $this->User->deleteActivationKey ....
$this->Auth->login($this->User->read());
$this->Session->setFlash(__('Successfully activated account. You are now logged in.'));
$this->User->saveField('last_login', date('Y-m-d H:i:s') );
$this->redirect(array('controller' => 'pages'));
...
到目前为止,这一直有效,直到您想使用身份验证组件的 user() 函数获取有关登录用户的信息。
我们在 AppController->beforeRender 中使用它,以在应用程序范围内获取用户信息:
$this->set('auth', $this->Auth->user());
但是在自动登录操作之后,我收到了 undefined index 通知。 (例如,通过在 View 中访问 $auth['id'] )。 print_r() 仅显示当前用户的用户名和哈希密码。 如果您手动登录,一切正常。肯定是账号激活后自动登录的东西。
session 似乎有问题?我做错了什么?
最佳答案
在测试了许多变体后找到了解决方案。
现在适用于:
$user = $this->User->findById($id);
$user = $user['User'];
$this->Auth->login($user);
不知道为什么,我以为我已经尝试过这种方法,但没有成功。
关于session - CakePHP 2.0 账户激活后自动登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9650605/