views:

253

answers:

5

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');
+1  A: 

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.

+3  A: 

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

IvanBernat
+4  A: 

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');
Alexander Morland
Thank you. This is exactly what I was looking for.
Horatio Alderaan
A: 

To access Auth vars in views just do it:

echo $session->read('Auth.User.id');
A: 

Thanks for this. I have to do $this->Session->read('Auth.User.username') because I am accessing it from a controller and I could not find a way to use session helper from inside a controller. How can I initialize and use session helper instead?

porto alet