如何使用ACL根据特定用户的权限(例如EDIT)过滤域对象列表


How do one use ACL to filter a list of domain-objects according to a certain user's permissions (e.g. EDIT)?

当在web应用程序中使用Symfony2中的ACL实现时,我们遇到了一个用例,其中使用ACL的建议方法(检查单个域对象上的用户权限)变得不可行的。因此,我们想知道是否存在ACL API的某些部分可以用来解决我们的问题。

用例位于一个控制器中,该控制器准备了要在模板中呈现的域对象列表,以便用户可以选择要编辑的对象。用户没有编辑数据库中所有对象的权限,因此必须对列表进行相应的过滤。

这可以(在其他解决方案中)根据以下两种策略完成:

1)一个查询过滤器,它在给定的查询中添加来自当前用户的对象(或多个对象)ACL的有效对象id。即:

WHERE <other conditions> AND u.id IN(<list of legal object ids here>)

2)一个后查询过滤器,在从数据库检索到完整的列表后,删除用户没有正确权限的对象。即:

$objs   = <query for objects>
$objIds = <getting all the permitted obj ids from the ACL>
for ($obj in $objs) {
    if (in_array($obj.id, $objIds) { $result[] = $obj; } 
}
return $result;

第一种策略更可取,因为数据库正在执行所有过滤工作,并且都需要两个数据库查询。一个用于acl,一个用于实际查询,但这可能是不可避免的。

Symfony2中是否实现了这些策略(或实现了期望的结果)?

假设您有一个想要检查的域对象集合,您可以使用security.acl.provider服务的findAcls()方法在isGranted()调用之前批量加载。

条件:

数据库中填充测试实体,从我的数据库中随机抽取一个用户,对象权限为MaskBuilder::MASK_OWNER,角色IS_AUTHENTICATED_ANONYMOUSLY的类权限为MASK_VIEW;MASK_CREATE for ROLE_USER;MASK_EDITMASK_DELETE代替ROLE_ADMIN

测试代码:

$repo = $this->getDoctrine()->getRepository('Foo'Bundle'Entity'Bar');
$securityContext = $this->get('security.context');
$aclProvider = $this->get('security.acl.provider');
$barCollection = $repo->findAll();
$oids = array();
foreach ($barCollection as $bar) {
    $oid = ObjectIdentity::fromDomainObject($bar);
    $oids[] = $oid;
}
$aclProvider->findAcls($oids); // preload Acls from database
foreach ($barCollection as $bar) {
    if ($securityContext->isGranted('EDIT', $bar)) {
        // permitted
    } else {
        // denied
    }
}

结果:

对于$aclProvider->findAcls($oids);的调用,分析器显示我的请求包含3个数据库查询(作为匿名用户)。

如果没有findAcls()的调用,同样的请求包含51个查询。

请注意,findAcls()方法以30个批量加载(每批2个查询),因此您的查询数量将随着更大的数据集而增加。这项测试在工作日结束后的15分钟内完成;当我有机会时,我将更彻底地浏览和审查相关方法,看看ACL系统是否还有其他有用的用途,并在这里报告。

如果你有几千个实体,遍历实体是不可行的——它会变得越来越慢,消耗更多的内存,迫使你使用条令批处理功能,从而使你的代码更复杂(而且无效,因为毕竟你只需要id来进行查询——而不是内存中的整个acl/实体)

我们解决这个问题的方法是替换acl。使用我们自己的Provider服务,并在该服务中添加一个方法来直接查询数据库:

private function _getEntitiesIdsMatchingRoleMaskSql($className, array $roles, $requiredMask)
{
    $rolesSql = array();
    foreach($roles as $role) {
        $rolesSql[] = 's.identifier = ' . $this->connection->quote($role);
    }
    $rolesSql =  '(' . implode(' OR ', $rolesSql) . ')';
    $sql = <<<SELECTCLAUSE
        SELECT 
            oid.object_identifier
        FROM 
            {$this->options['entry_table_name']} e
        JOIN 
            {$this->options['oid_table_name']} oid ON (
            oid.class_id = e.class_id
        )
        JOIN {$this->options['sid_table_name']} s ON (
            s.id = e.security_identity_id
        )     
        JOIN {$this->options['class_table_nambe']} class ON (
            class.id = e.class_id
        )
        WHERE 
            {$this->connection->getDatabasePlatform()->getIsNotNullExpression('e.object_identity_id')} AND
            (e.mask & %d) AND
            $rolesSql AND
            class.class_type = %s
       GROUP BY
            oid.object_identifier    
SELECTCLAUSE;
    return sprintf(
        $sql,
        $requiredMask,
        $this->connection->quote($role),
        $this->connection->quote($className)
    );
} 

然后从获取实体id的实际公共方法调用此方法:

/**
 * Get the entities Ids for the className that match the given role & mask
 * 
 * @param string $className
 * @param string $roles
 * @param integer $mask 
 * @param bool $asString - Return a comma-delimited string with the ids instead of an array
 * 
 * @return bool|array|string - True if its allowed to all entities, false if its not
 *          allowed, array or string depending on $asString parameter.
 */
public function getAllowedEntitiesIds($className, array $roles, $mask, $asString = true)
{
    // Check for class-level global permission (its a very similar query to the one
    // posted above
    // If there is a class-level grant permission, then do not query object-level
    if ($this->_maskMatchesRoleForClass($className, $roles, $requiredMask)) {
        return true;
    }         
    // Query the database for ACE's matching the mask for the given roles
    $sql = $this->_getEntitiesIdsMatchingRoleMaskSql($className, $roles, $mask);
    $ids = $this->connection->executeQuery($sql)->fetchAll('PDO::FETCH_COLUMN);
    // No ACEs found
    if (!count($ids)) {
        return false;
    }
    if ($asString) {
        return implode(',', $ids);
    }
    return $ids;
}

现在我们可以使用下面的代码为DQL查询添加过滤器:

// Some action in a controller or form handler...
// This service is our own aclProvider version with the methods mentioned above
$aclProvider = $this->get('security.acl.provider');
$ids = $aclProvider->getAllowedEntitiesIds('SomeEntityClass', array('role1'), MaskBuilder::VIEW, true);
if (is_string($ids)) {
   $queryBuilder->andWhere("entity.id IN ($ids)");
}
// No ACL found: deny all
elseif ($ids===false) {
   $queryBuilder->andWhere("entity.id = 0")
}
elseif ($ids===true) {
   // Global-class permission: allow all
}
// Run query...etc

缺点:考虑到ACL继承和策略的复杂性,必须改进该方法,但对于简单的用例,它工作得很好。还必须实现缓存以避免重复的双重查询(一个是类级查询,另一个是对象级查询)

将Symfony ACL耦合回应用程序并使用它作为排序,这不是一个好方法。您正在混合和耦合2或3层应用程序在一起。ACL的功能是回答"是/否"的问题,"我可以这样做吗?"如果您需要某种类型的拥有/可编辑的文章,您可以使用来自另一个表的CreatedBy或组CreatedBy标准等列。一些用户组或帐户

使用连接,如果您正在使用Doctrine,让它为您生成连接,因为它们几乎总是更快。因此,您应该设计您的ACL模式,使这些快速过滤器是可行的。

相关文章: