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

Using and configuring the Auth component


If there is something that defines the Auth component, it is its flexibility that accounts for different types of authentication modes, each of these modes serving different needs. In this recipe, you will learn how to modify the component's default behavior, and how to choose between the different authentications modes.

Getting ready

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

We will also add support to have disabled user accounts. Add a field named active to your users table with the following SQL statement:

ALTER TABLE `users`
ADD COLUMN `active` TINYINT UNSIGNED NOT NULL default 1;

How to do it...

  1. 1. Modify the definition of the Auth component in your AppController class, so it looks like the following:

    public $components = array(
    'Auth' => array(
    'authorize' => 'controller',
    'loginRedirect' => array(
    'admin' => false,
    'controller' => 'users',
    'action' => 'dashboard'
    ),
    'loginError' => 'Invalid account specified',
    'authError' => 'You don\'t have the right permission'
    ),
    'Session'
    );
    
  2. 2. Now while still editing your app/app_controller.php file, place the following code right below the components property declaration, at the beginning of the beforeFilter method in your AppController class:

    public function beforeFilter() {
    if ($this->Auth->getModel()->hasField('active'))
    {$this->Auth->userScope = array('active' => 1);
    }
    }
    
  3. 3. Copy the default layout from cake/libs/view/layouts/default.ctp to your app/views/layouts directory, and make sure you place the following line in your layout where you wish to display authentication messages:

    <?php echo $this->Session->flash('auth'); ?>
    
  4. 4. Edit your app/controllers/users_controller.php file and place the following method right below the logout() method:

    public function dashboard() {
    }
    
  5. 5. Finally, create the view for this newly added action in a file named dashboard.ctp and place it in your app/views/users folder with the following contents:

    <p>Welcome!</p>
    

    If you now browse to http://localhost/users/login and enter the wrong credentials (wrong username and/or password), you should see the error message shown in the following screenshot:

How it works...

As the Auth component does its magic right before a controller action is executed, we either need to specify its settings in the beforeFilter callback, or pass them in an array when adding the component to the components property. A common place to do it is in the beforeFilter() method of the AppController class, as by doing so we can share the same authentication settings throughout all our controllers.

This recipe changes some Auth settings, so that whenever a valid user logs in, they are automatically taken to a dashboard action in the UsersController (done via the loginRedirect setting.) It also adds some default error messages through the component's respective settings: loginError for when the given account is invalid, and authError for when there is a valid account, but the action is not authorized (which can be achieved by returning false from the isAuthorized() method implemented in AppController.)

It also sets the component's userScope setting in AppController::beforeFilter(). This setting allows us to define which conditions the User find operation need to match to allow a user account to log in. By adding the userScope setting, we ensure that only user records that have the active field set to 1 are allowed access.

Changing the default user model

As you may have noticed, the role of the User model is crucial, not only to fetch the right user account, but also to check the permissions on some of the authentication schemes. By default, the Auth component will look for a User model, but you can change which model is to be used by setting the userModel property or the userModel key in the settings array.

For example, if your user model is Account, you would add the following setting when adding the Auth component to your controller:

'userModel' => 'Account'

Or equivalently, you would add the following to the beforeFilter method of your AppController class, in the block of code where you are setting up the component:

$this->Auth->userModel = 'Account';

There's more...

The $authorize property of the Auth component (or the authorize key in the Auth component settings array) defines which authentication scheme should be used. Possible values are:

  • controller: It makes the component use the controller's isAuthorized method, which returns true to allow access, or false to reject it. This method is particularly useful when obtaining the logged-in user (refer to the Getting the current user's information recipe)

  • model: It is similar to controller; instead of using the controller to call the method, it looks for the isAuthorized method in the User model. First, it tries to map the controller's action to a CRUD operation (one of'create', 'read', 'update', or'delete'), and then calls the method with three arguments: the user record, the controller that is being accessed, and the CRUD operation (or actual controller action) that is to be executed.

  • object: It is similar to model; instead of using the model to call the method, it looks for the isAuthorized method in a given class. In order to specify which class, set the AuthComponent::$object property to an instance of such a class. It calls the method with three arguments: the user record, the controller that is being accessed, and the action that is to be executed.

  • actions: It uses the Acl component to check for access, which allows a much more grained access control.

  • crud: It is similar to actions; the difference lies in the fact that it first tries to map the controller's action to a CRUD operation (one of'create', 'read', 'update', or'delete'.)

See also

  • Getting the current user's information

  • Setting up Access Control Layer based authentication