Book Image

CakePHP 1.3 Application Development Cookbook

Book Image

CakePHP 1.3 Application Development Cookbook

Overview of this book

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying web applications. While the framework has a lot of documentation and reference guides available for beginners, developing more sophisticated and scalable applications require a deeper knowledge of CakePHP features, a challenge that proves difficult even for well established developers.The recipes in this cookbook will give you instant results and help you to develop web applications, leveraging the CakePHP features that allow you to build robust and complex applications. Following the recipes in this book you will be able to understand and use these features in no time. We start with setting up authentication on a CakePHP application. One of the most important aspects of a CakePHP application: the relationship between models, also known as model bindings. Model binding is an integral part of any application's logic and we can manipulate it to get the data we need and when we need. We will go through a series of recipes that will show us how to change the way bindings are fetched, what bindings and what information from a binding is returned, how to create new bindings, and how to build hierarchical data structures. We also define our custom find types that will extend the three basic ones, allowing our code to be even more readable and also create our own find type, with pagination support. This book also has recipes that cover two aspects of CakePHP models that are fundamental to most applications: validation, and behaviors.
Table of Contents (17 chapters)
CakePHP 1.3 Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface

Saving the user details after login


One of the most typical functionalities offered by sites with authentication capabilities is the ability to let the user choose (by clicking on a checkbox) whether they want the system to remember their account after logging in.

Getting ready

We should have a working authentication system, so follow the entire recipe, Setting up a basic authentication system.

How to do it...

  1. 1. Edit your app/app_controller.php file and add the following Auth component settings to the Auth component. Also add the Cookie component by making the following changes to the components property: AppController (in the $components property) must include the following mandatory setting (if it is not there, add it inside the array of settings for the component):

    public $components = array(
    'Auth' => array(
    'authorize' => 'controller',
    'autoRedirect' => false
    ),
    'Cookie',
    'Session'
    );
    
  2. 2. Edit your app/views/users/login.ctp view file and make the following changes:

    <?php
    echo $this->Form->create(array('action'=>'login'));
    echo $this->Form->inputs(array(
    'legend' => 'Login',
    'username',
    'password',
    'remember' => array('type' => 'checkbox', 'label' => 'Remember me')
    ));
    echo $this->Form->end('Login');
    ?>
    
  3. 3. Now, add the following code to the end of the login action of your UsersController class:

    if (!empty($this->data)) {
    $userId = $this->Auth->user('id');
    if (!empty($userId)) {
    if (!empty($this->data['User']['remember'])) {
    $user = $this->User->find('first', array(
    'conditions' => array('id' => $userId),
    'recursive' => -1,
    'fields' => array('username', 'password')
    ));
    $this->Cookie->write('User', array_intersect_key(
    $user[$this->Auth->userModel],
    array('username'=>null, 'password'=>null)
    ));
    } elseif ($this->Cookie->read('User') != null) {
    $this->Cookie->delete('User');
    }
    $this->redirect($this->Auth->redirect());
    }
    }
    
  4. 4. Next, add the following code to the beginning of the logout() method of your UsersController class:

    if ($this->Cookie->read('User') != null) {
    $this->Cookie->delete('User');
    }
    
  5. 5. Finally, add the following method to your AppController class, right below the components property declaration:

    public function beforeFilter() {
    if ($this->Auth->user() == null) {
    $user = $this->Cookie->read('User');
    if (!empty($user)) {
    $user = $this->Auth->getModel()->find('first', array(
    'conditions' => array(
    $this->Auth->fields['username'] => $user[$this->Auth->fields['username']],
    $this->Auth->fields['password'] => $user[$this->Auth->fields['password']]
    ),
    'recursive' => -1
    ));
    if (!empty($user) && $this->Auth->login($user)) {
    $this->redirect($this->Auth->redirect());
    }
    }
    }
    }
    

How it works...

The first task we needed to accomplish was to disable the automatic redirect in the Auth component. By doing so, we are able to catch both successful and failed log in attempts, which allows us to check if they remember me checkbox is selected. If the checkbox is indeed checked, we create a cookie named User that contains the values for the username and password fields with a value equal to the user ID that logged in. Remember that the password value is automatically encrypted by the Auth component, so it is safe for storage. The Cookie component adds another layer of security by automatically encrypting and decrypting the given values.

In AppController::beforeFilter(), when there is no logged-in user, we check to see if the cookie is set. If it is, we use the values for the username and password fields stored in the cookie to log in a user, and then redirect the browser to the login action.

Finally, we delete the cookie when it is appropriate (when a user logs in without the checkbox selected, or when the user manually logs out).

See also

  • Getting the current user's information