Refreshing the Auths session
Friday, April 3rd 2009, 1:40am
Topics: Tutorials, CakePHP
Tags: Auth, Session, Refresh
Comments: 3
Permalink -
Tinylink
If you have developed with the Auth Component 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 App Controller. It can refresh the whole session or just a single key in the session.
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 Session Component and a User Model.
This should work fine for the time being, or at least until the Cake Team adds a refresh method to the Auth Component. Cheers.
/**
* Refreshes the Auth session
* @param string $field
* @param string $value
* @return void
*/
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 Session Component 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 Auth Component. Cheers.
3 Comments
webbedcoes.co.uk
Feb 10th 2011, 02:18
Dec 28th 2011, 22:04
thanks.
Jan 8th, 21:29