Code snippets for symfony 1.x


Refine Tags

Snippets tagged "credentials"

modified hasCredential method that loads permissions from the database

Tired of having to signout / signin your users to reload permissions? This method fetches the credentials directly from the database so the credential changes are effective as soon as the groups or permissions are changed.

Paste this in your lib/myUser.class.php file

   * Overridden method that actually reads the permission from DB
   * instead of relying on data present when the user logs in.
   * @param  string  permission name
   * @return boolean true if the user has credential
  public function hasCredential($permission_name)
    if (!$this->isAuthenticated()) {
      return false;
    $gu = $this->getGuardUser();
    $groups = $gu->getGroups();
    $permissions = $gu->getPermissions();
    $permission_names = array();
    foreach($permissions as $permission) {
      $permission_names[] = $permission->getName();
    foreach($groups as $group) {
      $group_permissions = $group->getPermissions();
      foreach($group_permissions as $group_permission) {
        $permission_names = array_merge($permission_names, array($group_permission->getName()));
    $permission_names = array_unique($permission_names);
    return (in_array($permission_name, $permission_names)) ? true : false;
by Mathieu Comandon on 2011-02-07, tagged credentials  sfdoctrineguardplugin  sfguarduser 

Alternative security module

For some applications, the basic security layer offered by symfony is insufficient - often a database describes users organised into groups or hierarchical groups, and a way is needed to translate this into a symfony mechanism. Luckily this is quite easy: a filter can be implemented that redirects if the necessary auth criteria have not been met.

You will need to modify this to match your own objects, but it may be good to get you started. Place it in apps/frontend/lib/myDatabaseSecurityFilter.class.php:

 * Trying something to implement a database security layer
 * 24 May 2006 - initial version
class myDatabaseSecurityFilter extends sfBasicSecurityFilter
  public function execute($filterChain)
    // A call may be made up of several subcalls, so limit this to just the first one
    if ($this->isFirstCall()) {
      $context = $this->getContext();
      $user = $context->getUser();
      $strUser = $user->getUsername();
      $strModule = $context->getModuleName();
      $strRoute = $strModule . '/' . $context->getActionName();
      // Only do security check if the module is security-enabled (which is default, so
      // use 'none' to turn it off
      $strParam = "mod_${strModule}_db_security";
      $boolSec = sfConfig::get($strParam);
      if ($boolSec !== 'none') {
        // Get the UserMain object for this user
        $objUserMain = $user->getUserMain();
        $objFuncs = $objUserMain->getUserFunctions($strRoute);
        // If the above checks did not OK this op, then refuse access
        if (count($objFuncs) < 1)
          $fCtrllr = '';
          if (!sfConfig::get('sf_no_script_name')) $fCtrllr = getenv('SCRIPT_NAME');

Basically, this filter looks up a yaml config value on a per-module basis, called mod_<module>_db_security, and if it is set to 'none', then allows the filter to pass through. If it is not, it looks up the database user object (which for convenience I am keeping within my sfUser object) and performs a query called getUserFunctions(), which looks up the current module/action and determines whether this is allowed.

A redirect is called if no explicit authorisation is held, otherwise the module passes control to the next filter.

Then to install it, simply put:

  class: myDatabaseSecurityFilter

in your apps/frontend/config/filters.yml file.

by halfer on 2006-06-20, tagged credentials  owner  security 
(1 comment)

How to add HTTP Auth to symfony

Here is a little hack to use http auth when credentials or auth is insufficient:

public function executeSecure()
    if (!$this->getUser()->hasAttribute("secure_referer"))
        $this->getUser()->setAttribute("secure_referer", $this->getRequest()->getReferer());
    if (!isset($_SERVER['PHP_AUTH_USER']))
      header('WWW-Authenticate: Basic realm="Member Area"');
      header('HTTP/1.0 401 Unauthorized');
      return sfView::NONE;
        if ($this->getUser()->tryLogin($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']))
            return $this->redirect($this->getUser()->getAttribute("secure_referer"));
          header('WWW-Authenticate: Basic realm="Member Area"');
          header('HTTP/1.0 401 Unauthorized');
          return sfView::NONE;

No template is needed, as everytime you access it will redirect to the referer. Then change in app/yourapp/config/settings.yml the secure_module and secure_action to match this module.

You will need a myUser::tryLogin function that returns a boolean saying "auth is ok" or "bad auth"

And then you're done :p

[from my Wiki Post ab out that]

by Romain Dorgueil on 2006-05-25, tagged authentication  credentials  http  user 

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:

  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))
    // 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