Something you will inevitably need to do when using the CakePHP Auth Component is to refresh the Auth user data that is stored in the session, for example after a user has updated their email address or other personal/login details. The docs don’t make it obvious how to do this, but a quick search led me to various Stackoverflow questions and this blog post by MilesJ, which is quite old, so presumably refers to CakePHP 1.3. MilesJ’s solution looked like a good one, so I thought I would use this and adapt it as necessary for Cake 2.x.
The things that needed to be changed were as follows:
- To get the Auth SessionKey, you must now use
AuthComponent::$sessionKey
- Instead of
ClassRegistry::init('User')
to load the User model , you need to use$this->loadModel('User');
- Rather than passing the result from read() (containing the user data array as subarray of the ‘User’ index in the array that is returned), straight to the login method, it is necessary for the user data to be at the top level of the array that passed. Therefore, it is necessary to get the user data and then pass the $user[‘User’] array to the login method. It took me a while to work this out, during which time I was getting very frustrated with being logged out whenever I updated my details, and this was why.
This gives us the following function, which seems to do the trick for me:
/** * Refreshes the Auth session * Modified from MilesJ: http://milesj.me/blog/read/refreshing-auth * @param string $field * @param string $value * @return void */ protected function _refreshAuth($field = '', $value = '') { if (!empty($field) && !empty($value)) { //Update just a single field in the Auth session data $this->Session->write(AuthComponent::$sessionKey .'.'. $field, $value); } else { if (!isset($this->User)) { $this->loadModel('User'); //Load the User model, if it is not already loaded } $user = $this->User->read(false, $this->Auth->user('id')); //Get the user's data $this->Auth->login($user[User']); //Must have user data at top level of array that is passed to login method } }