1
votes

I'm using CakePHP v2.4...

I want to make a single db request to set a $currentuser variable which I can reference in all my controllers. This seems like it should be easy, but it's giving me a hard time because $this->Auth->user() is not available in the beforeFilter of AppController when a user logs in. So that variable will be useless immediately after someone logs in (until they reload the page , etc). afterFilter() and beforeRender() happen after the other controller actions, so that doesn't solve my issue.

What's the right way to do this?

3

3 Answers

2
votes

You don't have to do another query, just instead configure the authentication adapter to fetch the data for you:

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'contain' => array(
                    // Whatever you want here
                    'Profile',
                    'Setting'
                )
            )
        )
    )
);

All your current logged in user data is then already available through:

$this->Auth->user()

Even if you don't redirect and if you do it will be still there.

You should use this way to access the user data over directly accessing the session because the user component abstracts it properly. See:

Why CakeSession::read() is not the best choice:

If your're not using a session based authentication system CakeSession::read("Auth.User"); will break. It will also break if the Auth session key changes for some reason, unlikely but not impossible.

Also calling the static CakeSession::read("Auth.User") method is not best practice here either. The session component can be extended and you can access the customized SessionComponent still through $this->Session using aliasing.

Overall I would avoid adding statics and singletons into my methods - it makes it hard to test them or change them. I would always wrap them in a method. This way you can mock them in a test.

1
votes

I access current logged in user in my app this way:

CakeSession::read("Auth.User");

It's in my AppController::beforeFilter()

0
votes
$this->Session->read('Auth.User')

This should be available in all those locations as well as views.