Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to get AuthComponent user data from a view in CakePHP?

According to the cakebook section on the Auth component, I can implement simple authentication by using the following Users controller:

class UsersController extends AppController {

    var $name = 'Users';    
    var $components = array('Auth'); // Not necessary if declared in your app controller

    /**
     *  The AuthComponent provides the needed functionality
     *  for login, so you can leave this function blank.
     */
    function login() {
    }

    function logout() {
        $this->redirect($this->Auth->logout());
    }
}

I would like to be able to something like the following into my view:

<?php
   $username = $auth->user('username');
   echo "Welcome " . $username;
?>

Is there a simple way to do this, or do I need to overwrite the login function and store the username to the session?

Update

Alexander's answer is exactly what I wanted. However, I will add the following in case someone else gets confused like I did.

It took me a while to understand that if you change the model that Auth uses (for example, you might have a 'persons' table instead of 'users'), then you need to use something like:

$persondata = $session->read('Auth.Person');
like image 257
Horatio Alderaan Avatar asked May 30 '09 06:05

Horatio Alderaan


3 Answers

Actually this information is easily available from the session. You use the session helper to grab it. I believe the correct syntax is :

$userdata = $session->read('Auth.User');
$username = $session->read('Auth.User.username');

EDIT:

For CakePHP 2.X and on the syntax is:

$userdata = $this->session->read('Auth.User');
$username = $this->session->read('Auth.User.username');
like image 171
Alexander Morland Avatar answered Sep 29 '22 16:09

Alexander Morland


Check out AuthComponent-Methods in the CakePHP manual....

You can access an user info after a user has logged in from the session via $this->Auth->User(). So if you want the username, just use this in the controller.

$this->set('username', $this->Auth->User('username'));

You can now use $username in the view.

like image 20
Vince Avatar answered Sep 29 '22 17:09

Vince


Add a method in your AppController

function beforeFilter() {
$ath = $this->Auth->user();
$this->set('userDetails', $ath['User']);
}

And then you can access it from your views and/or layouts via $userDetails

like image 25
unicorn_crack Avatar answered Sep 29 '22 16:09

unicorn_crack