1
votes

I am using cakephps Auth Component to login to my site. When I correctly enter in my username and password, it will log me in. Then when I use loggedIn() to check that I am logged in, it is very inconsistent in returning true. This is my AppController where I set loggedIn() to a variable to use later:

<?php

App::uses('Controller', 'Controller');
App::uses('File', 'Utility');
App::uses('AuthComponent', 'Component');

class AppController extends Controller {
    public $components = array(
        'Session',
        'Auth'=>array(
            'loginRedirect'=> array('controller'=>'users', 'action'=>'index'),
            'logoutRedirect'=> array('controller'=>'users', 'action'=>'index'),
            'authError' =>"You can't access that page",
            'authorize'=> array('Controller')
        )

    );
    //determines what logged in users have access to
    public function isAuthorized($user){
        return true;
    }
    //determines what non-logged in users have access to
    public function beforeFilter(){
        $this->Auth->allow('index','view');
        $this->set('logged_in', $this->Auth->loggedIn());
        $this->set('current_user', $this->Auth->user());
    }


}

And here is a bit of my code where I use 'logged_in'

<?php if($logged_in): ?> //this only returns true some of the time
      Welcome <?php echo $current_user['username']; ?>. <?php echo  $this->Html->link('Logout', array('controller'=>'users', 'action'=>'login')); ?>

<?php else: ?>
   <?php echo  $this->Html->link('Login', array('controller'=>'users', 'action'=>'logout')); ?>
<?php endif; ?>

And here is my login():

public function login(){
    if($this->request->is('post')){
        if($this->Auth->login()){  //this returns true every time
            $this->redirect($this->Auth->redirect());

        }else{
            $this->Session->setFlash('Your username and/or password is incorrect');
        }
    }

}

I have tried calling $this->Auth->loggedIn() instead of using $logged_in but I get the error that the Auth Helper cannot be found. Please let me know if there is any more information needed to answer my question.

1
Just look if there there is an authenticated with your var current_user - Hugo Dozois

1 Answers

1
votes

Move these lines to beforeRender()

    $this->set('logged_in', $this->Auth->loggedIn());
    $this->set('current_user', $this->Auth->user());

Besides that, nothing seems wrong with your code. The comment that Auth->login() would always return true only happens when you pass any argument to the login() method, which the code you show doesnt have though.