Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "owner dynamiccredentials"

Simulate a 'owner' security credential

The Problem

Let's say your site manages users who can create posts. You want to restrict the edition of a post to the administrator or the owner of the post. You would therefore like to have a security.yml file that looks like:

edit:
  is_secure:on
  credentials: [[administrator owner]]

but the problem is that the credentials are given to the user statically upon login.

The solution

The solution is therefore to give or take back credentials dynamically. As of now, the only way to achieve that is to “hijack” the getCredential action of the sfAction class.

Write the following in the action file of your post module:

// to put in the actions.class.php file
function getCredential()
  {
    $this->post = $this->_retrievePost(); // retrieving the object based on the request parameters
    if ($this->getUser()->isOwnerOf($this->post))
      $this->getUser()->addCredential('owner');
    else
      $this->getUser()->removeCredential('owner');
 
    // the hijack is over, let the normal flow continue:
    return parent::getCredential();
  }

Of course you will have to write the sfUser::isOwnerOf function, which depends on your data structure. You will also have to write the _retrievePost function that returns null if no post have been found. Watch out for the isOwnerOf function: it has to return true if the post is new, otherwise users will never be able to create new posts.

Now the owner of a post can edit his post but not the others ones, except if he has administrator credentials. Everything is set up in the security.yml file. For example it is now trivial to add the same security check for the delete method.

by Olivier Verdier on 2006-05-25, tagged credentials  dynamiccredentials  owner  security 
(10 comments)