2015-10-04 100 views
0

我有一个页面,我可以修改用户详细信息(用户名,名字,头像...)。 我在我的导航栏中有一个关于当前登录用户信息的元素。事情是我无法弄清楚如何在数据修改后立即刷新会话。CakePHP 3刷新会话数据

UsersController

public function edit($id = null) 
{ 
    if (!$id) { 
     throw new NotFoundException(__('Invalid user')); 
    } 

    $user = $this->Users->get($id); 
    if ($this->request->is(['post', 'put'])) { 
     $this->Users->patchEntity($user, $this->request->data); 
     if ($this->Users->save($user)) { 

      //REFRESH SESSION ????\\ 
      $this->request->session()->write('Auth.User', $user); 
      //\\ 

      $this->Flash->success(__('User has been updated.')); 
      return $this->redirect(['action' => 'edit/' . $id]); 
     } 
     $this->Flash->error(__('Unable to update User details.')); 
    } 

    $this->set(compact('user')); 
} 

回答

7

只需更新它,你会在洛时,即使用AuthComponent::setUser()设置同样的方式。

此外,只有在编辑过的用户实际上是当前登录的用户的情况下,您也可以这样做。并且您希望以与Auth组件相同的格式设置数据,即(现在),作为一个数组,并出于安全的目的,没有密码。

,它假定名为id单个列的主键,并将其命名password

if ($this->Auth->user('id') === $user->id) { 
    $data = $user->toArray(); 
    unset($data['password']); 

    $this->Auth->setUser($data); 
} 

参见

+2

'unset($ data ['password'])'不应该是必须的,因为它应该位于实体内部的隐藏属性中。 –

+0

@StefanD。在一个理想的世界中,无论烘焙功能在一个月前是否被破解(烘烤1.1.4),人们甚至可能不会使用烘焙和/或使用“token”,“password”以外的列和'passwd'(这是什么烘烤检测),所以我说它仍然值得一提的是,人们应该留意这一点。 – ndm