Welcome to the Cookbook

loading...

10.2.8 Logging in

Our application is now under access control, and any attempt to view non-public pages will redirect you to the login page. However, we will need to create a login view before anyone can login. Add the following to app/views/users/login.ctp if you haven't done so already.

<h2>Login</h2>
<?php
echo $form->create('User', array('url' => array('controller' => 'users', 'action' =>'login')));
echo $form->input('User.username');
echo $form->input('User.password');
echo $form->end('Login');
?>
  1. <h2>Login</h2>
  2. <?php
  3. echo $form->create('User', array('url' => array('controller' => 'users', 'action' =>'login')));
  4. echo $form->input('User.username');
  5. echo $form->input('User.password');
  6. echo $form->end('Login');
  7. ?>

If a user is already logged in, redirect him:

function login() {
	if ($this->Session->read('Auth.User')) {
		$this->Session->setFlash('You are logged in!');
		$this->redirect('/', null, false);
	}
}       
  1. function login() {
  2. if ($this->Session->read('Auth.User')) {
  3. $this->Session->setFlash('You are logged in!');
  4. $this->redirect('/', null, false);
  5. }
  6. }

You may also want to add a flash() for Auth messages to your layout. Copy the default core layout - found at cake/libs/view/layouts/default.ctp - to your app layouts folder if you haven't done so already. In app/views/layouts/default.ctp add

$session->flash('auth');
  1. $session->flash('auth');

You should now be able to login and everything should work auto-magically. When access is denied Auth messages will be displayed if you added the $session->flash('auth')