WpDoe
WpDoe

Reputation: 474

'Error: Call to a member function allow() on a non-object' in CakePHP 3 AuthComponent

Following the CakePHP which looks a bit confusing and not so straight forward, I have created a basic authentication logic, however, I cannot seem to load Auth component.

Here is the code part from the AppController.php:

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
            'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]],
            'loginAction' => ['controller' => 'Users', 'action' => 'login'],
            'loginRedirect' => ['controller' => 'Groups', 'action' => 'index'],
            'logoutRedirect' => ['controller' => 'Users', 'action' => 'login']
    ]);  
}


//Allow basic views

public function beforeFilter(Event $event)
{
    $this->Auth->allow(['index', 'view', 'display']);
}

Now no matter which controller or action I run, I always receive the following error:

Error: Call to a member function allow() on a non-object 

that is referencing the following line:

$this->Auth->allow(['index', 'view', 'display']);

It has to be a straight forward thing, but I just cannot find it in the docummentation, therefore any help or guidance is much appreciated.

Upvotes: 3

Views: 2398

Answers (2)

ptica
ptica

Reputation: 747

I've got this one when I had no Template/Users/login.ctp template created yet

managed to find out only after inspecting the stack-trace obtained by

$e = new \Exception('How did I got here anyway?');
debug($e->getTraceAsString());

yielding

#5 vendor/cakephp/cakephp/src/Error/ExceptionRenderer.php(318): Cake\Controller\Controller->render('missingTemplate')

Upvotes: 0

Inigo Flores
Inigo Flores

Reputation: 4469

Check that your child controller's method initialize() is calling the parent method.

class MyController extends AppController
{
    public function initialize() {
        parent::initialize();
        //rest of code
    }
}

Upvotes: 3

Related Questions