Single Login For Multiple User Types with CakePHP

I started working on a project that requires a single login for multiple user types. Because of the way my mind organizes things, I was having difficulty getting my mind around multiple models pointing to the same table in the database. It just felt messy. But I found this to be the best solution. I can provide single user login and keep the user functionality separated.

In this case, I have managers and tenants both pointing to the users table. I simply add a ‘type’ column to the user table to track what type of user it is. Then in my callback methods on the models, I set the conditions for the beforeFind and the beforeSave within each model to it’s corresponding type. This keeps both the data it displays and the data it saves in check and accurate. Here is what my manager model looks like.

<?php
class Manager extends AppModel {

 var $name = 'Manager';
 var $useTable = 'users';

 // only return users where type = Manager
 function beforeFind($queryData) {
$queryData['conditions']['Manager.type'] = 'Manager';
return $queryData;
 }

 // Ensure the Type is set to Manager before saving this record
 function beforeSave() {
$this->data['Manager']['type'] = 'Manager';
return true;
 }

}

?>

The same would apply to the tenants model. This works like a charm. It helps to provide excellent separation between user types without writing a lot of extra code to manage and check for the differences in user types.

Happy coding!

Like it? Post to your favorite location and share.
  • Digg
  • del.icio.us
  • Facebook
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitter

2 Comments

Kim Pomares  on August 12th, 2010

So elegant!

My question: I have 4 different types of users: Guests, Members, Staff Members and System Administrators.

In my StaffMember model, I would like my beforeFind to return Staff members and Administrators.

I amusing ['group_id'] instead of ['type'] in my table, with a groups table and the group names.

$queryData['conditions']['StaffMember.group_id'] = ‘> 5′;

But what I get is all users who have a blank group_id.

Kim Pomares  on August 12th, 2010

Got it!

$queryData['conditions']['StaffMember.group_id'] = ‘> 5?;

becomes:

$queryData['conditions'] = array(‘StaffMember.group_id >’ => ’5′);

:-)

Leave a Comment

You must be to post a comment.