Welcome to the Cookbook

loading...

5.1.3 Defining Permissions: Cake's Database ACL

There is no translation yet for this section. Please help out and translate this.. More information about translations

Now that we've covered INI-based ACL permissions, let's move on to the (more commonly used) database ACL.

5.1.3.1 Getting Started

There is no translation yet for this section. Please help out and translate this.. More information about translations

The default ACL permissions implementation is database powered. Cake's database ACL consists of a set of core models, and a console application that comes with your Cake installation. The models are used by Cake to interact with your database in order to store and retrieve nodes in tree format. The console application is used to initialize your database and interact with your ACO and ARO trees.

To get started, first you'll need to make sure your /app/config/database.php is present and correctly configured. See section 4.1 for more information on database configuration.

Once you've done that, use the CakePHP console to create your ACL database tables:

$ cake schema run create DbAcl

Running this command will drop and re-create the tables necessary to store ACO and ARO information in tree format. The output of the console application should look something like the following:

---------------------------------------------------------------
Cake Schema Shell
---------------------------------------------------------------

The following tables will be dropped.
acos
aros
aros_acos

Are you sure you want to drop the tables? (y/n) 
[n] > y
Dropping tables.
acos updated.
aros updated.
aros_acos updated.

The following tables will be created.
acos
aros
aros_acos

Are you sure you want to create the tables? (y/n) 
[y] > y
Creating tables.
acos updated.
aros updated.
aros_acos updated.
End create.

This replaces an older deprecated command, "initdb".

You can also use the SQL file found in app/config/sql/db_acl.sql, but that's nowhere near as fun.

When finished, you should have three new database tables in your system: acos, aros, and aros_acos (the join table to create permissions information between the two trees).

If you're curious about how Cake stores tree information in these tables, read up on modified database tree traversal. The ACL component uses CakePHP's Tree Behavior to manage the trees' inheritances. The model class files for ACL are all compiled in a single file db_acl.php.

Now that we're all set up, let's work on creating some ARO and ACO trees.

5.1.3.2 Creating Access Request Objects (AROs) and Access Control Objects (ACOs)

There is no translation yet for this section. Please help out and translate this.. More information about translations

In creating new ACL objects (ACOs and AROs), realize that there are two main ways to name and access nodes. The first method is to link an ACL object directly to a record in your database by specifying a model name and foreign key value. The second method can be used when an object has no direct relation to a record in your database - you can provide a textual alias for the object.

In general, when you're creating a group or higher level object, use an alias. If you're managing access to a specific item or record in the database, use the model/foreign key method.

You create new ACL objects using the core CakePHP ACL models. In doing so, there are a number of fields you'll want to use when saving data: model, foreign_key, alias, and parent_id.

The model and foreign_key fields for an ACL object allows you to link up the object to its corresponding model record (if there is one). For example, many AROs will have corresponding User records in the database. Setting an ARO's foreign_key to the User's ID will allow you to link up ARO and User information with a single User model find() call if you've set up the correct model associations. Conversely, if you want to manage edit operation on a specific blog post or recipe listing, you may choose to link an ACO to that specific model record.

The alias for an ACL object is just a human-readable label you can use to identify an ACL object that has no direct model record correlation. Aliases are usually useful in naming user groups or ACO collections.

The parent_id for an ACL object allows you to fill out the tree structure. Supply the ID of the parent node in the tree to create a new child.

Before we can create new ACL objects, we'll need to load up their respective classes. The easiest way to do this is to include Cake's ACL Component in your controller's $components array:

var $components = array('Acl');
  1. var $components = array('Acl');

Once we've got that done, let's see what some examples of creating these objects might look like. The following code could be placed in a controller action somewhere:

While the examples here focus on ARO creation, the same techniques can be used to create an ACO tree.

Keeping with our Fellowship setup, let's first create our ARO groups. Because our groups won't really have specific records tied to them, we'll use aliases to create these ACL objects. What we're doing here is from the perspective of a controller action, but could be done elsewhere. What we'll cover here is a bit of an artificial approach, but you should feel comfortable using these techniques to build AROs and ACOs on the fly.

This shouldn't be anything drastically new - we're just using models to save data like we always do:

function anyAction()
{
	$aro =& $this->Acl->Aro;
	
	//Here's all of our group info in an array we can iterate through
	$groups = array(
		0 => array(
			'alias' => 'warriors'
		),
		1 => array(
			'alias' => 'wizards'
		),
		2 => array(
			'alias' => 'hobbits'
		),
		3 => array(
			'alias' => 'visitors'
		),
	);
	
	//Iterate and create ARO groups
	foreach($groups as $data)
	{
		//Remember to call create() when saving in loops...
		$aro->create();
		
		//Save data
		$aro->save($data);
	}

	//Other action logic goes here...
}
  1. function anyAction()
  2. {
  3. $aro =& $this->Acl->Aro;
  4. //Here's all of our group info in an array we can iterate through
  5. $groups = array(
  6. 0 => array(
  7. 'alias' => 'warriors'
  8. ),
  9. 1 => array(
  10. 'alias' => 'wizards'
  11. ),
  12. 2 => array(
  13. 'alias' => 'hobbits'
  14. ),
  15. 3 => array(
  16. 'alias' => 'visitors'
  17. ),
  18. );
  19. //Iterate and create ARO groups
  20. foreach($groups as $data)
  21. {
  22. //Remember to call create() when saving in loops...
  23. $aro->create();
  24. //Save data
  25. $aro->save($data);
  26. }
  27. //Other action logic goes here...
  28. }

Once we've got them in there, we can use the ACL console application to verify the tree structure.

$ cake acl view aro

Aro tree:
---------------------------------------------------------------
  [1]warriors

  [2]wizards

  [3]hobbits

  [4]visitors

---------------------------------------------------------------

I suppose it's not much of a tree at this point, but at least we've got some verification that we've got four top-level nodes. Let's add some children to those ARO nodes by adding our specific user AROs under these groups. Every good citizen of Middle Earth has an account in our new system, so we'll tie these ARO records to specific model records in our database.

When adding child nodes to a tree, make sure to use the ACL node ID, rather than a foreign_key value.

function anyAction()
{
	$aro = new Aro();
	
	//Here are our user records, ready to be linked up to new ARO records
	//This data could come from a model and modified, but we're using static
	//arrays here for demonstration purposes.
	
	$users = array(
		0 => array(
			'alias' => 'Aragorn',
			'parent_id' => 1,
			'model' => 'User',
			'foreign_key' => 2356,
		),
		1 => array(
			'alias' => 'Legolas',
			'parent_id' => 1,
			'model' => 'User',
			'foreign_key' => 6342,
		),
		2 => array(
			'alias' => 'Gimli',
			'parent_id' => 1,
			'model' => 'User',
			'foreign_key' => 1564,
		),
		3 => array(
			'alias' => 'Gandalf',
			'parent_id' => 2,
			'model' => 'User',
			'foreign_key' => 7419,
		),
		4 => array(
			'alias' => 'Frodo',
			'parent_id' => 3,
			'model' => 'User',
			'foreign_key' => 7451,
		),
		5 => array(
			'alias' => 'Bilbo',
			'parent_id' => 3,
			'model' => 'User',
			'foreign_key' => 5126,
		),
		6 => array(
			'alias' => 'Merry',
			'parent_id' => 3,
			'model' => 'User',
			'foreign_key' => 5144,
		),
		7 => array(
			'alias' => 'Pippin',
			'parent_id' => 3,
			'model' => 'User',
			'foreign_key' => 1211,
		),
		8 => array(
			'alias' => 'Gollum',
			'parent_id' => 4,
			'model' => 'User',
			'foreign_key' => 1337,
		),
	);
	
	//Iterate and create AROs (as children)
	foreach($users as $data)
	{
		//Remember to call create() when saving in loops...
		$aro->create();

		//Save data
		$aro->save($data);
	}
	
	//Other action logic goes here...
}
  1. function anyAction()
  2. {
  3. $aro = new Aro();
  4. //Here are our user records, ready to be linked up to new ARO records
  5. //This data could come from a model and modified, but we're using static
  6. //arrays here for demonstration purposes.
  7. $users = array(
  8. 0 => array(
  9. 'alias' => 'Aragorn',
  10. 'parent_id' => 1,
  11. 'model' => 'User',
  12. 'foreign_key' => 2356,
  13. ),
  14. 1 => array(
  15. 'alias' => 'Legolas',
  16. 'parent_id' => 1,
  17. 'model' => 'User',
  18. 'foreign_key' => 6342,
  19. ),
  20. 2 => array(
  21. 'alias' => 'Gimli',
  22. 'parent_id' => 1,
  23. 'model' => 'User',
  24. 'foreign_key' => 1564,
  25. ),
  26. 3 => array(
  27. 'alias' => 'Gandalf',
  28. 'parent_id' => 2,
  29. 'model' => 'User',
  30. 'foreign_key' => 7419,
  31. ),
  32. 4 => array(
  33. 'alias' => 'Frodo',
  34. 'parent_id' => 3,
  35. 'model' => 'User',
  36. 'foreign_key' => 7451,
  37. ),
  38. 5 => array(
  39. 'alias' => 'Bilbo',
  40. 'parent_id' => 3,
  41. 'model' => 'User',
  42. 'foreign_key' => 5126,
  43. ),
  44. 6 => array(
  45. 'alias' => 'Merry',
  46. 'parent_id' => 3,
  47. 'model' => 'User',
  48. 'foreign_key' => 5144,
  49. ),
  50. 7 => array(
  51. 'alias' => 'Pippin',
  52. 'parent_id' => 3,
  53. 'model' => 'User',
  54. 'foreign_key' => 1211,
  55. ),
  56. 8 => array(
  57. 'alias' => 'Gollum',
  58. 'parent_id' => 4,
  59. 'model' => 'User',
  60. 'foreign_key' => 1337,
  61. ),
  62. );
  63. //Iterate and create AROs (as children)
  64. foreach($users as $data)
  65. {
  66. //Remember to call create() when saving in loops...
  67. $aro->create();
  68. //Save data
  69. $aro->save($data);
  70. }
  71. //Other action logic goes here...
  72. }

Typically you won't supply both an alias and a model/foreign_key, but we're using both here to make the structure of the tree easier to read for demonstration purposes.

The output of that console application command should now be a little more interesting. Let's give it a try:

$ cake acl view aro

Aro tree:
---------------------------------------------------------------
  [1]warriors

    [5]Aragorn

    [6]Legolas

    [7]Gimli

  [2]wizards

    [8]Gandalf

  [3]hobbits

    [9]Frodo

    [10]Bilbo

    [11]Merry

    [12]Pippin

  [4]visitors

    [13]Gollum

---------------------------------------------------------------

Now that we've got our ARO tree setup properly, let's discuss a possible approach for structuring an ACO tree. While we can structure more of an abstract representation of our ACO's, it's often more practical to model an ACO tree after Cake's Controller/Action setup. We've got five main objects we're handling in this Fellowship scenario, and the natural setup for that in a Cake application is a group of models, and ultimately the controllers that manipulate them. Past the controllers themselves, we'll want to control access to specific actions in those controllers.

Based on that idea, let's set up an ACO tree that will mimic a Cake app setup. Since we have five ACOs, we'll create an ACO tree that should end up looking something like the following:

  • Weapons
  • Rings
  • PorkChops
  • DiplomaticEfforts
  • Ales

One nice thing about a Cake ACL setup is that each ACO automatically contains four properties related to CRUD (create, read, update, and delete) actions. You can create children nodes under each of these five main ACOs, but using Cake's built in action management covers basic CRUD operations on a given object. Keeping this in mind will make your ACO trees smaller and easier to maintain. We'll see how these are used later on when we discuss how to assign permissions.

Since you're now a pro at adding AROs, use those same techniques to create this ACO tree. Create these upper level groups using the core Aco model.

5.1.3.3 Assigning Permissions

There is no translation yet for this section. Please help out and translate this.. More information about translations

After creating our ACOs and AROs, we can finally assign permissions between the two groups. This is done using Cake's core Acl component. Let's continue on with our example.

Here we'll work in the context of a controller action. We do that because permissions are managed by the Acl Component.

class SomethingsController extends AppController
{
	// You might want to place this in the AppController
	// instead, but here works great too.

	var $components = array('Acl');

}
  1. class SomethingsController extends AppController
  2. {
  3. // You might want to place this in the AppController
  4. // instead, but here works great too.
  5. var $components = array('Acl');
  6. }

Let's set up some basic permissions using the AclComponent in an action inside this controller.

function index()
{
	//Allow warriors complete access to weapons
	//Both these examples use the alias syntax
	$this->Acl->allow('warriors', 'Weapons');
	
	//Though the King may not want to let everyone
	//have unfettered access
	$this->Acl->deny('warriors/Legolas', 'Weapons', 'delete');
	$this->Acl->deny('warriors/Gimli',   'Weapons', 'delete');
	
	die(print_r('done', 1));
}
  1. function index()
  2. {
  3. //Allow warriors complete access to weapons
  4. //Both these examples use the alias syntax
  5. $this->Acl->allow('warriors', 'Weapons');
  6. //Though the King may not want to let everyone
  7. //have unfettered access
  8. $this->Acl->deny('warriors/Legolas', 'Weapons', 'delete');
  9. $this->Acl->deny('warriors/Gimli', 'Weapons', 'delete');
  10. die(print_r('done', 1));
  11. }

The first call we make to the AclComponent allows any user under the 'warriors' ARO group full access to anything under the 'Weapons' ACO group. Here we're just addressing ACOs and AROs by their aliases.

Notice the usage of the third parameter? That's where we use those handy actions that are in-built for all Cake ACOs. The default options for that parameter are create, read, update, and delete but you can add a column in the aros_acos database table (prefixed with _ - for example _admin) and use it alongside the defaults.

The second set of calls is an attempt to make a more fine-grained permission decision. We want Aragorn to keep his full-access privileges, but deny other warriors in the group the ability to delete Weapons records. We're using the alias syntax to address the AROs above, but you might want to use the model/foriegn key syntax yourself. What we have above is equivalent to this:

// 6342 = Legolas
// 1564 = Gimli

$this->Acl->deny(array('model' => 'User', 'foreign_key' => 6342), 'Weapons', 'delete');
$this->Acl->deny(array('model' => 'User', 'foreign_key' => 1564), 'Weapons', 'delete');
  1. // 6342 = Legolas
  2. // 1564 = Gimli
  3. $this->Acl->deny(array('model' => 'User', 'foreign_key' => 6342), 'Weapons', 'delete');
  4. $this->Acl->deny(array('model' => 'User', 'foreign_key' => 1564), 'Weapons', 'delete');

Addressing a node using the alias syntax uses a slash-delimited string ('/users/employees/developers'). Addressing a node using model/foreign key syntax uses an array with two parameters: array('model' => 'User', 'foreign_key' => 8282).

The next section will help us validate our setup by using the AclComponent to check the permissions we've just set up.

5.1.3.4 Checking Permissions: The ACL Component

There is no translation yet for this section. Please help out and translate this.. More information about translations

Let's use the AclComponent to make sure dwarves and elves can't remove things from the armory. At this point, we should be able to use the AclComponent to make a check between the ACOs and AROs we've created. The basic syntax for making a permissions check is:

$this->Acl->check( $aro, $aco, $action = '*');
  1. $this->Acl->check( $aro, $aco, $action = '*');

Let's give it a try inside a controller action:

function index()
{
	//These all return true:
	$this->Acl->check('warriors/Aragorn', 'Weapons');
	$this->Acl->check('warriors/Aragorn', 'Weapons', 'create');
	$this->Acl->check('warriors/Aragorn', 'Weapons', 'read');
	$this->Acl->check('warriors/Aragorn', 'Weapons', 'update');
	$this->Acl->check('warriors/Aragorn', 'Weapons', 'delete');
	
	//Remember, we can use the model/foreign key syntax 
	//for our user AROs
	$this->Acl->check(array('model' => 'User', 'foreign_key' => 2356), 'Weapons');
	
	//These also return true:
	$result = $this->Acl->check('warriors/Legolas', 'Weapons', 'create');
	$result = $this->Acl->check('warriors/Gimli', 'Weapons', 'read');
	
	//But these return false:
	$result = $this->Acl->check('warriors/Legolas', 'Weapons', 'delete');
	$result = $this->Acl->check('warriors/Gimli', 'Weapons', 'delete');
}
  1. function index()
  2. {
  3. //These all return true:
  4. $this->Acl->check('warriors/Aragorn', 'Weapons');
  5. $this->Acl->check('warriors/Aragorn', 'Weapons', 'create');
  6. $this->Acl->check('warriors/Aragorn', 'Weapons', 'read');
  7. $this->Acl->check('warriors/Aragorn', 'Weapons', 'update');
  8. $this->Acl->check('warriors/Aragorn', 'Weapons', 'delete');
  9. //Remember, we can use the model/foreign key syntax
  10. //for our user AROs
  11. $this->Acl->check(array('model' => 'User', 'foreign_key' => 2356), 'Weapons');
  12. //These also return true:
  13. $result = $this->Acl->check('warriors/Legolas', 'Weapons', 'create');
  14. $result = $this->Acl->check('warriors/Gimli', 'Weapons', 'read');
  15. //But these return false:
  16. $result = $this->Acl->check('warriors/Legolas', 'Weapons', 'delete');
  17. $result = $this->Acl->check('warriors/Gimli', 'Weapons', 'delete');
  18. }

The usage here is demonstrational, but hopefully you can see how checking like this can be used to decide whether or not to allow something to happen, show an error message, or redirect the user to a login.