Refreshing the Auths session

This article is over a year old and may contain outdated information.

If you have developed with the AuthComponent at all, you would know by now that the auth session does not refresh when ever a user updates its information (such a drawback). This is extremely useful in many situations, especially when a user updates his profile, and you need to echo the new content in the views. I have written the following method, which should be placed in your AppController. It can refresh the whole session or just a single key in the session.

/**
 * Refreshes the Auth session
 * @param string $field
 * @param string $value
 * @return void 
 */
public function _refreshAuth($field = '', $value = '') {
	if (!empty($field) && !empty($value)) { 
		$this->Session->write($this->Auth->sessionKey .'.'. $field, $value);
	} else {
		if (isset($this->User)) {
			$this->Auth->login($this->User->read(false, $this->Auth->user('id')));
		} else {
			$this->Auth->login(ClassRegistry::init('User')->findById($this->Auth->user('id')));
		}
	}
}

To refresh the whole session, you would call this method in an action while passing no arguments. If you would like to refresh a users email, you would pass email as the first argument, and the new email as the second. This method assumes you are using the SessionComponent and a User model.

// Refresh whole session
if ($this->User->save($this->data)) {
    $this->_refreshAuth();
    $this->Session->setFlash('Your information has been updated!');
}

// Refresh single key
$this->_refreshAuth('email', $this->data['User']['email']);

This should work fine for the time being, or at least until the Cake Team adds a refresh method to the AuthComponent. Cheers.

3 Comments

  • Exactly what I was looking! Thanks for posting!
    Jagadeesh
  • Its works fine for updating auth but id you have a form validation it may not show the errors. I am using cPHP 1.3 and Its not showing validation errors.

    thanks.
    Ersin Demirtas
  • Nice function, this really helped me. thanks for posting!