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');
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');
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With