【问题标题】:Refresh User Session Array After Editing Information CAKEPHP编辑信息后刷新用户会话数组 CAKEPHP
【发布时间】:2013-02-13 15:16:12
【问题描述】:

我想知道在用户更新其信息后如何使数组 (Auth.User) 重新加载。

目前这不会发生,直到用户注销然后重新登录,因为那是它加载数组 (Auth.User) 的时候。

到目前为止,我已经尝试了一些解决方案such as

我也尝试过添加 $user = $this->User->field('name', array('User.id' => $this->Session->read('Auth.User.id'))); $this->Session->write('Auth.User', $user); 进入应用控制器。

但没有一个成功。

谢谢

【问题讨论】:

    标签: session cakephp cakephp-2.3


    【解决方案1】:

    你就在那里。请记住,返回的数组 $user 包含一个 'User' 键,例如:

    array(
      'User' => array(
        'id' => 1
      )
    )
    

    所以将它保存到Auth.User 下的会话实际上会像这样保存会话数组:

    array(
      'Auth' => array(
        'User' => array(
          'User' => array(
            'id' => 1
          )
        )
      )
    )
    

    相反,将其保存到 Auth 密钥中,您就可以像往常一样继续访问它:

    $user = $this->User->field('name', array(
      'User.id' => $this->Session->read('Auth.User.id')
    )); 
    $this->Session->write('Auth', $user);
    

    现在会话密钥已被清除,重新登录用户的方法更加简单快捷,正如 mark 在 cmets 中所说:使用 $this->Auth->login()

    $user = $this->User->field('name', array(
      'User.id' => $this->Session->read('Auth.User.id')
    )); 
    $this->Auth->login($user);
    

    【讨论】:

    • 你也可以只使用 $this->Auth->login($user);因为这也会更新身份验证会话数据
    • 是的,这绝对是漂亮的。我会把它添加到答案中。我的大脑还停留在 1.3 中。
    • 仅供参考,当您将数据发送到 Auth::login 时,您必须发送您的用户数据,而不是您的 user[usermodel] 数据,否则您会在您的身份验证会话中写入不好的内容。为了我的钱, Auth::login 应该知道您是在传递平面数组还是嵌套数组,但事实并非如此。因此,例如您需要这样做: $user = $this->UserModelClass->findById($userId); $this->Auth->login($user[$this->UserModelClass->alias]);
    【解决方案2】:

    就我而言,我使用的是 CakePHP 4,

    我已经加载了身份验证组件。

    我正在使用此代码来刷新我的身份验证信息。

    $user = (new UserService())->Users;
    $user = $user->find()->where(['Users.id' => $this->userId])->contain(['RELATION1', 'RELATION2'])->first();
    
    $this->Authentication->setIdentity($user);
    

    现在您可以使用...获取登录用户的数据了。

    $this->Authentication->getIdentity()->getOriginalData();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2021-03-14
      • 2021-10-01
      相关资源
      最近更新 更多