0

I'm using CakePHP 2.3 and here's my AppController.php and UsersController.php files, pieces that are relevant to user log in:

class AppController extends Controller {


public $helpers = array('Html', 'Form', 'Session');

   public $components = array(
      'RequestHandler',
      'Session',
      'Auth' => array(
          'loginRedirect' => array('controller' => 'dpts', 'action' => 'index'),
          'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
      )
  );

  public function beforeFilter() {
    $this->UserAuth->beforeFilter($this); // Error fires here.
    $authUser = $this->UserAuth->getUser();
    $this->set('loggedInUser', $authUser);
  }

}

=================================================================================

<?php
class UsersController extends AppController {
    public function login() {
        if ($this->request->is('post')) {            
            if ($this->Auth->login()) {
                $this->redirect(array('action' => 'index', 'controller' => 'pages'));
            } else {
                $this->Session->setFlash(__('Correo y/o contraseña incorrecta.'));
            }
        }
    }
}

How can I get the object of the user currently logged in?

I'm getting an error in the beforeFilter() of the AppController:

Fatal error: Call to a member function beforeFilter() on a non-object in C:\xampp\htdocs\testapp\app\Controller\AppController.php on line 50

0

1 Answer 1

2

You can use below code to get current user logged in information.

   function beforeFilter(){     
        $first_name = $this->Auth->user('first_name');
        $id = $this->Auth->user('id');
        $this->set('first_name', $first_name);
    }

Add code in AppController.php

5
  • Say I want to show a property in $authUser in a nav section in the Layouts/default.ctp file, where would I put this call if I want $authUser to be accesible in the layout file? I want to say something like "Welcome back, <?php echo $authUser['first_name']; ?>"
    – sergserg
    Apr 19, 2013 at 13:05
  • use beforeFilter() function for that and put it in Appcontroller.php like below function beforeFilter(){ $this->UserAuth->beforeFilter($this); $authUser = $this->UserAuth->getUser(); $this->set('authUser', $authUser); } Apr 19, 2013 at 13:08
  • I'm getting this error: Fatal error: Call to a member function beforeFilter() on a non-object in C:\xampp\htdocs\testapp\app\Controller\AppController.php on line 50 - I've edited my question with the code as it looks.
    – sergserg
    Apr 19, 2013 at 13:11
  • 1
    Check my modified answer.. Apr 19, 2013 at 13:23
  • 1
    @Serg it's better to use the 'static' interface of the AuthComponent. I described this in another question here on StackOverflow: stackoverflow.com/questions/16096176/…
    – thaJeztah
    Apr 19, 2013 at 23:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.