lucasnadalutti
lucasnadalutti

Reputation: 5948

Session not set in beforeFilter() when having authComponent

I have a problem in my CakePHP application which is that there is no Session object available in my AppController beforeFilter() function, but only when I have Auth Component in it. I have the following code to set the site's language:

public function beforeFilter() {
    $this->_setLanguage();
    $locale = Configure::read('Config.language');
    $path = APP . 'View' . DS . $locale . DS . $this->viewPath;
    if ($locale && file_exists($path)) {
        $this->viewPath = $locale . DS . $this->viewPath;
    }
}

protected function _setLanguage() {
    if (!$this->Session->check('Config.language')) {
        $langLetters = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en';
        $browserLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
        switch ($browserLanguage){
            case "en":
                $this->Session->write('Config.language', 'en');
                break;
            case "pt":
                $this->Session->write('Config.language', 'pt');
                break;
            default:
                $this->Session->write('Config.language', 'en');
        }
    }
    Configure::write('Config.language', $this->Session->read('Config.language'));
}

Problem is that, when I add:

public $components = array('Auth');

I get the following error:

Fatal error: Call to a member function check() on a non-object in /home/brasilgameshow/www/teste_credenciamento/app/Controller/AppController.php on line 73

which is the first line of the _setLanguage() function. That means that I simply don't have the Session object anymore when Auth component is present. Could anybody suggest a workaround which wouldn't compromise Auth component's security? I mean, would simply initializing a new session when there is none set be a good solution?

Upvotes: 0

Views: 317

Answers (2)

Ayman Bedair
Ayman Bedair

Reputation: 937

By default if you don't add any components CakePHP would load its default components (Session)

When you tried to invoke your own components array (with Auth in this case) you should include all other components you may need

Upvotes: 2

lucasnadalutti
lucasnadalutti

Reputation: 5948

SOLUTION FOUND

As Ayman pointed at the comments, when adding your own array of components in AppController, Session needs to be included! Thanks!

Upvotes: 0

Related Questions