Ben Murden

Tag: acl

CakePHP ACL and Groups

by on Sep.23, 2011, under Development

There are many great tutorials out there to help you get started with the arcane ACL features of CakePHP, but none of them seemed to cover a specific problem that occurs with reassignment of a parent_id on a save operation.

The parent_id would revert to being null on some save operations on the User model, so if, for example, the user changed their password, they’d end up with no group and an infinite redirect; the redirect loop occurring because everyone should be in a group. Upon investigation with a debugger on task, I discovered the problem resides with the parentNode function, and that all other examples out there are written with the expectation that a group_id will be present in every save operation.

Since parentNode is always called on a save operation performed on a model acting as an ARO, some modification of the typical example is necessary to ensure that you’ll always have the group_id available for finding the parent node ID.

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

Like in the Change Password example, on pages where user data is changed, but the group_id is not needed, the parent_id can now be found for the User ARO. On the other hand, you won’t overwrite the group_id if the data indicated it should be changed.

Hope people find this useful, and if you have any suggestions for improvements, let me know!

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!