Code snippets for symfony 1.x


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 

Comments on this snippet

gravatar icon
#1 Jason Ibele on 2006-06-20 at 03:08

Awsome snippet, thanks Halfer!