11
votes

I am using CakePHP 2.0's integrated Auth component. I have the following tables :

  • Users
  • Groups
  • Profiles

My model relations are as follows:

User belongsTo Group
User hasMany Profiles

While logged in to the site, I noticed the Auth session contains only User table information, but I need the information of Groups and Profiles tables too for the logged in user.

Is there any way to do that with the Auth component?

3

3 Answers

7
votes

There is no way to do this with the AuthComponent because of the way it handles the session keys. You can, however, just save it to the session yourself.

The only way to do this is to add to the session when the user logs in:

function login() {
    if ($this->Auth->login($this->data)) {
        $this->User->id = $this->Auth->user('id');
        $this->User->contain(array('Profile', 'Group'));
        $this->Session->write('User', $this->User->read());
    }
}

Then in your beforeFilter() in your AppController, save a var for the controllers to get to:

function beforeFilter() {
    $this->activeUser = $this->Session->read('User');
}

// and allow the views to have access to user data
function beforeRender() {
    $this->set('activeUser', $this->activeUser);
}

Update: As of CakePHP 2.2 (announced here), the AuthComponent now accepts the 'contain' key for storing extra information in the session.

1
votes

As far as I'm aware the Auth component only caches the data from your Users model. You can use that information to retrieve the desired data from the other models, by for example using this in your controller:

$group_data = $this->Group->findById($this->Auth->user('group_id'));

Or

$profile_data = $this->Profile->findByUserId($this->Auth->user('id'));

But I don't think you can get it from the Auth component directly, as it doesn't cache the related model data out of the box.

1
votes

Two ways:

1) Extend the FormAuthenticate class (see /Controller/Component/Auth) or whatever you use to login and override the _findUser() method and tell the Auth component to use this authorize class. See this page how to do all of that http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

2) Simply implement a method in the model that will fetch all data you want and call it in the login method of your controller and write the data into the session. IMO it is handy to have such a method because sometimes you need to refresh the session data anyways.

Because of your comment on the other answer:

You will have to write a method and some code in a model that will return you the data. CakePHP can't read your mind and a database without code. No matter which of both suggested ways you're going to use, you'll have to write code.