【问题标题】:CakePHP - Auth - $current_user - no ID, first_name, last_name etcCakePHP - Auth - $current_user - 没有 ID、名字、姓氏等
【发布时间】:2012-07-09 09:53:11
【问题描述】:

当我登录时:

$this->Auth->login($this->request->data)

现在,当我说:

$this->set('current_user', $this->Auth->user());

在我的 $current_user 中只有用户名和密码。在我的数据库中没有 ID、first_name、last_name 等。为什么?我需要那些数据!

我尝试了 $this->Auth->login() - 没有 $this->request->data 但没用。

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.1


    【解决方案1】:

    您不需要将请求数据发送给登录函数,如果匹配,它将根据当前的帖子数据返回一个用户。

    这是我的 UserController.php 中的登录功能

    public function login() {
        if($this->Auth->user()) {
            $this->redirect('/');
        }
    
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Invalid username or password.'));
            }
        }
    }
    

    为了在视图中查找我的用户字段,我在 AppController.php 中这样设置:

    class AppController extends Controller {
    
        public function beforeFilter() {
            $this->set('user', $this->Auth->user());
        }
    
    }
    

    那么$user 在您的所有视图中都可用。

    index.ctp
    
    if($user) {
        echo var_dump($user);
    }
    
    array
      'id' => string '15' (length=2)
      'created' => string '2012-06-29 21:50:44' (length=19)
      'modified' => string '2012-06-29 21:50:44' (length=19)
      'group_id' => string '1' (length=1)
      'username' => string 'user' (length=4)
      'email' => string 'email@email.com' (length=15)
    
    echo $user['id']; -> 15
    echo $user['email']; -> email@email.com
    

    【讨论】:

    • 出色的答案。我必须开始发布示例。 +1
    【解决方案2】:

    Auth::login() 方法在 2.0 中的工作方式发生了变化。您现在不需要将 post 数据传递给 login 方法,它会自动从请求对象中获取数据。

    更多信息请看这里的红框:http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2019-06-05
      • 2017-03-01
      • 2016-08-22
      • 1970-01-01
      相关资源
      最近更新 更多