Extending ACL to per field

10 10 2007

In some recent comments I was asked how I would expand ACL to incorporate rights at a per field level. I can see how this would be useful, although in my opinion it would become too unweidly for the admin to assign rights. It would be easier for the administrators to have multiple actions/views with the appropriate fields in them. I will outline both methods and there relative merits.

ACL per Field

The complex and ugly part of this method is the administration interface. The actual creation of ACO’s and access control can be done quite elgantly in Cake using a behaviour. All this requires is that in Model::afterSave() each fields ACO is created. Similarly for access control, in Model::afterFind() loop over each field, check the current users permissions and then unset the fields that are restricted.


  • This method allows very fine grained control. Each record will have it’s fields able to be restricted independantly of other records of the same model
  • When access rules change, views and actions don’t


  • Greater ACL overhead
  • ACO table grows much faster with respect to number of model records.
  • Views bedome more complex (logic to test which fields are available)
  • Unweidly managment interface

Actions per Rols

This method creates seperate actions/views based on the current users role, similar to the way admin_ works. There are two options with this method. Seperate actions and views per role, or seperate views only through $this->render($role.’_’.$action). Personally I would use the seperate views only as this does not require creating Route rules – yes I am lazy 🙂


  • Simplified logic. One extra line per action and no extra ACL overhead.
  • Simplified management
  • Field control at the Model level, not record level


  • Field access must be determined at design time
  • When rights change, so do views


While the first method provide far greater control over field rights at a record level, I feel that it is overkill and not worth the extra ACL and database overhead. In my experience, per user per record per field control has never been required. The simplified view switch method provides more than enough control for the majority of applications.

I find that access control is usually defined before implementation, and rarely changes while in production. This makes the trade of simplified code and management with the need to update files in the event of rights changes worth while.

What I’ve learnt over the last two months

19 09 2007

The last two months have been pretty hectic for me. I work full-time and also foolishly decided to do a full work load at university this semester as well. I found that the two don’t go togethter so well. Funny that. So I have learn’t the hard way that time managment is a skill and is a very hard skill to master.

Here are just a couple of other random things I have found out over the last few weeks:

  • Outlook Addins are a pain to develop – in managed code at least. I hear using unmanaged Win32 API is actually easier
  • Multiply that by 10 when deploying your addin in a terminal services environment
  • Never “port” an Access “application” to .NET. It is best to start from scratch and do it properly
  • Organising a group university assignment is a project in and of itself
  • Dragging yourself out of bed at 5 in the morning to go for a run eventually gets easier
  • Puppies are the cutest thing, but also the most annoying thing. Although I have taught her to sit

The good news is that I am starting a rather large CakePHP project very soon, so expect to see some more regular Cake posts in the near future.

Oh and dont forget to check out the new CakePHP Podcast “The Show“. Put a voice to those Cake characters we all know. The podcast has a good vibe to it and is actually really informative, e.g. I didn’t know that Cake 1.2 can handle XML natively in models. Jeff does a good job of interviewing Nate and gwoo in the pilot about the new features in the upcoming 1.2 version.

Update on DbAcl ticket #2976

27 08 2007

Wow – ask and you shall recieve. Not long after I posted this, changset 5588 implemented Simons patch.

One of the things that I have noticed about DbAcl, and other people have mentioned it as well on the Google Group, is that apart from not handling non-unique aliases very well, DbAcl node lookup will fail if the url does not have the full path in the ACO tree.

For example, consider the following tree.

|_ controller1
|_ controller 2
  |_action 1

If you then access http://localhost/controller1/ everything is fine. But when you try to access http://localhost/controller1/action1 you will get errors from DbAcl something like:
Warning (512): DB_ACL::check() - Failed ACO node lookup in permissions check.

Ok so just put all the actions in the database was my first solution. That is until I realised that something like /posts/view/id is going to need an ACO for every id, which seems a bit overkill.

What I would like is for non-existent children ACOs to automatically inherit from the parent and so on. Obviously this is only suitable for ACOs based on urls.

Simon Jaillet has submitted a new patch to the the CakePHP Trac Ticket #2976. Simon describes his reasons for creating the patch in his post and goes on to describe his own ACL implementation.

The patch that Simon has submitted resolves the inheritence problem. Simon also submitted an updated test case that contains tests specifically for non-existent children. I have tested this patch against the updated test cases and on some actual applications and I highly recommend updating to the latest svn trunk (5588 at time of update).applying this patch – at least until it makes it into the core. Which I sincerely hope that it does.

Kudos to Simon Jaillet, you are my new Acl hero having solved the inheritence problem for me.

Vendors in CakePHP

8 08 2007

While looking around just now I found a post complaining about vendors for not working like regular Cake magic includes such as the association variables.

This is from the original post

But I become strange when I tried to attach some personal library. They develop a shit name “vendor” to connect external library. This is really bad news because they just attach this file with the script and if you have attached a class you have to call the class to make object.

They then go on to complain that they can’t use Cakes database functions in their libraries. If you are writing code “libraries” specifically for CakePHP then it should probably be a Component, Behaviour or Helper.

The reason vendors() is the way it is is because Cake makes no assumptions about 3rd party classes or libraries.

For example: vendors(‘my_library’) will load my_library.php but there my not be a MyLibrary class in the file. In fact there may not even be any classes in there. Therefore Cake cannot automagically create a $this->MyLibrary variable.

When using vendors() you are left to use the library the old fashioned php way. i.e load, instatiate, use.

Cake makes things easy but it cannot support every configuration in every third party library. Sometimes you just have to do it yourself.

Multi-record Forms

6 08 2007

One question that comes up time and again on the Google Group is “How do I make a single form for more than one record?”, which I call multi-record forms. Multi-record forms have a repeated section in the form for multiple entries of the same data. The example that I am going to use is an Author with many Books.

In CakePHP this technique will be most commonly used with hasMany associations. Note that this technique is not specific to CakePHP but the code and conventions used are.

Building the Form

Our example form consists of an Authors name, date of birth and up to 5 book records with title, year of publication and publisher.

Here is the view.

<form action="<?= $html->url('/authors/add'); ?>" method="post">
    <legend>Author Details</legend>
    <?= $form->input('Author.name'); ?>
    <?= $form->input('Author.dob', array('type' => 'date')); ?>
    <legend>Books Published</legend>
    <?php for ($i=0; $i<5; $i++) : ?>
      <legend>Book<?= $i; ?></legend>
      <label for="BookTitle<?= $i; ?>">Title</label> <input type="text" name="data[Book][<?= $i; ?>][title]" id="BookTitle<?= $i; ?>" />
      <?= $form->error('Book.'.$i.'.title'); ?><br />
      <label for="BookPublication<?= $i; ?>">Publication Year</label> <input type="text" name="data[Book][<?= $i; ?>][publication]" id="BookPublication<?= $i; ?>" />
      <?= $form->error('Book.'.$i.'.publication'); ?><br />
      <label for="BookPublisher<?= $i; ?>">Publisher</label> <input type="text" name="data[Book][<?= $i; ?>][publisher]" id="BookPublisher<?= $i; ?>" />
      <?= $form->error('Book.'.$i.'.publisher'); ?>
    <?php endfor; ?>

The first fieldset is the Author details and is a constructed like a regular form. The Books Published fieldset contains 5 sub-fieldsets that are created by a loop.

Each sub-fieldset contains inputs with names in the format:
N.B. Notice that there are no quotes surrounding the text in the square brackets.

Using existing Data

For an edit page the majority of the view would be the same. The loop would change to:

<?php for ($i=0; $i<count($this->data['Book']); $i++) : ?>
  <legend>Book<?= $i; ?></legend>
  <input type="hidden" name="data[Book][<?= $i; ?>][id]" id="BookId<?= $i; ?>" value="<?= $this->data['Book'][$i]['id']; ?>" />
  <label for="BookTitle<?= $i; ?>">Title</label> <input type="text" name="data[Book][<?= $i; ?>][title]" id="BookTitle<?= $i; ?>" value="<?= $this->data['Book'][$i]['title']; ?>" />
  <?= $form->error('Book.'.$i.'.title'); ?><br />
  <label for="BookPublication<?= $i; ?>">Publication Year</label> <input type="text" name="data[Book][<?= $i; ?>][publication]" id="BookPublication<?= $i; ?>" value="<?= $this->data['Book'][$i]['publication']; ?>" />
  <?= $form->error('Book.'.$i.'.publication'); ?><br />
  <label for="BookPublisher<?= $i; ?>">Publisher</label> <input type="text" name="data[Book][<?= $i; ?>][publisher]" id="BookPublisher<?= $i; ?>" value="<?= $this->data['Book'][$i]['publisher']; ?>" />
  <?= $form->error('Book.'.$i.'.publisher'); ?>
<?php endfor; ?>

We simply changed the loop to terminate when all the books have been looped over, added a value attribute to the inputs and added an hidden id field so that our records get updated correctly.

Saving the Submitted Form

To save the submitted form we loop over each index in the Books array and save it to the database with the authors id.

It is important that Model::create() gets called during each iteration otherwise you will end up inserting on the first iteration and then updating each subsequent iteration.

By using Model::set() we can take advantage of validation rules in the model. However, any validation error messages wont be associated with the correct Book fields. To get around this we manually invoke Model::validates() and if this fails we reassign the invalid fields to a temporary array. Then if there are any errors we feed this temporary array back to the model so that the view has the correct data.

function add(){
  if (!empty($this->data)) {
    if ($this->Author->save()) {
      // grab the id of the Author we just saved
      $author_id = $this->Author-id;
      $invalidBookFields = array();
      foreach($this->data['Book'] as $index => $book) {
        $book = array('Book' => $book);
        $book['Book']['author_id'] = $author_id;

        // clear any previous Book data
        // We set the Book data this way so that validation is processed correctly
        if (!$this->Author->Book->validates()) {
          // save the validationErrors and reset for the next iteration
          $invalidBookFields[$index] = $this->Author->Book->validationErrors;
        } else {
      if (empty($invalidBookFields)) {
      	// success - set message or redirect
      } else {
      	// put all the errors back in the model so they make it back to the view
      	$this->Author->Book->validationErrors = $invalidBookFields;


If you need to make sure that all Books are valid before saving any of them you will need to loop the Books array twice. The first loop should validate each Book, then if there are no errors the second loop saves each Book.

If you do not know before hand how many items you need on your form you can use javascript or AJAX to dynamically add form elements as you need them.

Firefox Logo Crop Circle

23 07 2007

Just found this while playing around in Google Maps My Maps feature. A 67 metre Firefox logo as a crop circle.


Its been around since August 2006 and apparently it’s not the first of such stunts by a Linux user group at Oregon State University. When they do a job they do it properly, – they went all out with helicopters and planes documenting the process.

Link to the groups site.

ACL with Groups

19 07 2007

In a previous article I explained how to use the AclBehavior to create models that can be used for ACL.

Now the situation is – I want to assign permission to groups and have Users be a member of a group. I thought this would be easy using the AclBehavior. Turns out I was right, but it took me while to realise I was right.

So we are going to use the following Group model. It should look familiar. The database has a parent_id field in the groups table. This model allows us to create a heirachy of group roles.

class Group extends AppModel {
  var $name = 'Group';
  var $actsAs = array('Acl');

  function parentNode(){
    if (!$this->id) {
      return null;
    $data = $this->read();
    if (!$data['Group']['parent_id']){
      return null;
    } else {
      return $data['Group']['parent_id'];


Now, for ACL to work the easy way, we need to have our users in the Aro table as well. In your users table you need a field called group_id, and then use the belongsTo association to relate the user to a group. We also need to use the AclBehavior to get our users into the aro table.

Thats all pretty simple and straight forward. The trick is making the user aros children of a group aro. The parentNode() function is where the magic happens. Instead of returning a single id, you return an array with a two keys: model and foreign_key. This will allow the AclBehavior to locate the appropriate parent Aro node.

class User extends AppModel {
  var $name = 'User';
  var $belongsTo = array('Group');
  var $actsAs = array('Acl');

  function parentNode(){
    if (!$this->id) {
      return null;
    $data = $this->read();
    if (!$data['User']['group_id']){
      return null;
    } else {
      return array('model' => 'Group', 'foreign_key' => $data['User']['group_id']);


Now your User Aros are children of Group Aros. Simply assign permissions to the Group Aros and the Users will automatically inherit them.