Reputation: 631
when using
$user = $this->Auth->user();
to get the details about the currently logged in user, sometimes the returned array is like:
> user
> User
> Office
Message
and other times it's:
> user
id
name
> Office
This is annoying because in my view I output the users name and sometimes it's an extra level down in the array because of the extra ['User'] and sometimes it's not.
How can I control this or understand how I can know which version to expect?
thanks
EDIT here's my login action
public function login() {
$this->layout = 'loginlayout';
if ($this->request->is('post')) {
if ($this->Auth->login()) {
// did they select the remember me checkbox? - http://stackoverflow.com/questions/12447487/cakephp-remember-me-with-auth
if ($this->request->data['User']['remember_me'] == 1) {
// remove "remember me checkbox"
unset($this->request->data['User']['remember_me']);
// hash the user's password
$this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
// write the cookie
$this->Cookie->write('remember_me_cookie', $this->request->data['User'], true, '4 weeks');
}
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(('Username or password is incorrect'));
}
}
}
Also In my app controller's before filter I have:
if (!$this->Auth->loggedIn() && $this->Cookie->read('remember_me_cookie')) {
$cookie = $this->Cookie->read('remember_me_cookie');
$user = $this->User->find('first', array(
'conditions' => array(
'User.email' => $cookie['email'],
'User.password' => $cookie['password']
)
));
if ($user && !$this->Auth->login($user)) {
$this->redirect('/users/logout'); // destroy session & cookie
}
}
Is it possible that logging in via the cookie causes this different result?
Upvotes: 0
Views: 227
Reputation: 21743
So
$this->Auth->login($user)
is a bad idea if you want your Auth session data to be always in that structure as it is from login() itself. And you already knew that it adds an additional "User" key. So all you needed to do was to debug() the $user data and you would have seen that it needs to be
$this->Auth->login($user['User'])
PS: it is also documented in the cookbook, by the way. And also in the code when you look at the source code.
Upvotes: 2