【问题标题】:FOSUserBundle and ACL Business RoleFOSUserBundle 和 ACL 业务角色
【发布时间】:2012-03-31 15:44:08
【问题描述】:

这个周末我开始学习 Symfony 2。我没有遇到任何问题,因为我认为该框架有据可查。

我正在为 ACL 使用 FOSUserBundle 包。我想知道是否可以使其类似于 Yii 框架:

$bizRule='return Yii::app()->user->id==$params["post"]->authID;';
$task=$auth->createTask('updateOwnPost','update a post by author himself',$bizRule);
$task->addChild('updatePost');

您可以在上面的 sn-p 上看到所有详细信息。

如何使用 Symfony 2 实现类似的功能?这可能吗?

【问题讨论】:

  • 如果我理解正确,您希望能够将帖子的编辑/更新限制为该帖子的作者?我对 Yii 不熟悉,所以我在这里有点摸不着头脑。
  • @Problematic - 完全正确。 Yii ACL 方法允许您提供业务规则(如我的问题中的 sn-p 所示)。它会自动检查记录的用户 ID 是否等于从数据库中选择的帖子的 authID(或任何其他列)。你知道 Symfony 2 中的类似功能吗?

标签: symfony yii acl fosuserbundle


【解决方案1】:

Symfony2 有一个开箱即用的ACL system 可以做到这一点。为了完整起见,我包含了相关代码(修改为Post,而不是文档中的Comment):

public function addPostAction()
{
    $post = new Post();

    // setup $form, and bind data
    // ...

    if ($form->isValid()) {
        $entityManager = $this->get('doctrine.orm.default_entity_manager');
        $entityManager->persist($post);
        $entityManager->flush();

        // creating the ACL
        $aclProvider = $this->get('security.acl.provider');
        $objectIdentity = ObjectIdentity::fromDomainObject($post);
        $acl = $aclProvider->createAcl($objectIdentity);

        // retrieving the security identity of the currently logged-in user
        $securityContext = $this->get('security.context');
        $user = $securityContext->getToken()->getUser();
        $securityIdentity = UserSecurityIdentity::fromAccount($user);

        // grant owner access
        $acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
        $aclProvider->updateAcl($acl);
    }
}

本质上,您授予当前登录用户对 Post 实体的所有权(包括编辑权限)。然后检查当前用户是否有编辑权限:

public function editPostAction(Post $post)
{
    $securityContext = $this->get('security.context');

    // check for edit access
    if (false === $securityContext->isGranted('EDIT', $post))
    {
        throw new AccessDeniedException();
    }

    // retrieve actual post object, and do your editing here
    // ...
}

强烈建议您通读Access Control ListAdvanced ACL Concepts 食谱以获取更多信息。如上所示的 ACL 的实际创建非常冗长,我一直在努力 open-source ACL manager 以减轻痛苦……它“有点工作”;它是早期的测试版,需要很多的爱,所以使用风险自负。

【讨论】:

  • 如果我的回答对您有所帮助,请随时使用答案顶部附近的箭头和复选标记进行投票并接受。谢谢。
猜你喜欢
  • 2016-10-11
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-20
相关资源
最近更新 更多