在我的项目中,我需要将角色层次结构存储在数据库中并动态创建新角色.在Symfony2中security.yml,默认情况下存储角色层次结构.我发现了什么:
有一个服务security.role_hierarchy(Symfony\Component\Security\Core\Role\RoleHierarchy); 此服务在构造函数中接收角色数组:
public function __construct(array $hierarchy)
{
$this->hierarchy = $hierarchy;
$this->buildRoleMap();
}
Run Code Online (Sandbox Code Playgroud)
这家$hierarchy酒店是私人的.
\Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension::createRoleHierarchy()
正如我所理解的那样,这个参数来自构造函数,其中使用了config中的角色:
$container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']);
在我看来,最好的方法是从数据库中编译一组角色并将其设置为服务的参数.但我还没有明白该怎么做.
我看到的第二种方法是定义我自己RoleHierarchy继承自基类的类.但是因为在基RoleHierarchy类中$hierarchy属性被定义为私有,所以我必须重新定义基RoleHierarchy类中的所有函数.但我认为这不是一个好的OOP和Symfony方式......
zIs*_*zIs 38
解决方案很简单.首先,我创建了一个Role实体.
class Role
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $name
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="Role")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
**/
private $parent;
...
}
Run Code Online (Sandbox Code Playgroud)
之后创建了一个RoleHierarchy服务,从Symfony本地服务扩展而来.我继承了构造函数,在那里添加了一个EntityManager,并提供了一个原始构造函数,其中包含一个新的角色数组而不是旧的数组:
class RoleHierarchy extends Symfony\Component\Security\Core\Role\RoleHierarchy
{
private $em;
/**
* @param array $hierarchy
*/
public function __construct(array $hierarchy, EntityManager $em)
{
$this->em = $em;
parent::__construct($this->buildRolesTree());
}
/**
* Here we build an array with roles. It looks like a two-levelled tree - just
* like original Symfony roles are stored in security.yml
* @return array
*/
private function buildRolesTree()
{
$hierarchy = array();
$roles = $this->em->createQuery('select r from UserBundle:Role r')->execute();
foreach ($roles as $role) {
/** @var $role Role */
if ($role->getParent()) {
if (!isset($hierarchy[$role->getParent()->getName()])) {
$hierarchy[$role->getParent()->getName()] = array();
}
$hierarchy[$role->getParent()->getName()][] = $role->getName();
} else {
if (!isset($hierarchy[$role->getName()])) {
$hierarchy[$role->getName()] = array();
}
}
}
return $hierarchy;
}
}
Run Code Online (Sandbox Code Playgroud)
......并将其重新定义为服务:
<services>
<service id="security.role_hierarchy" class="Acme\UserBundle\Security\Role\RoleHierarchy" public="false">
<argument>%security.role_hierarchy.roles%</argument>
<argument type="service" id="doctrine.orm.default_entity_manager"/>
</service>
</services>
Run Code Online (Sandbox Code Playgroud)
就这样.也许,我的代码中有一些不必要的东西.也许有可能写得更好.但我认为,这个主要观点现在很明显.
man*_*ixx 14
我做了同样的事情,比如zIs(将RoleHierarchy存储在数据库中),但是我不能像zIs那样在构造函数中加载完整的角色层次结构,因为我必须在kernel.request事件中加载自定义的doctrine过滤器.构造函数将在之前被调用,kernel.request因此对我来说是没有选择的.
因此,我检查了安全组件,发现Symfony调用自定义根据用户角色Voter检查roleHierarchy:
namespace Symfony\Component\Security\Core\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
/**
* RoleHierarchyVoter uses a RoleHierarchy to determine the roles granted to
* the user before voting.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RoleHierarchyVoter extends RoleVoter
{
private $roleHierarchy;
public function __construct(RoleHierarchyInterface $roleHierarchy, $prefix = 'ROLE_')
{
$this->roleHierarchy = $roleHierarchy;
parent::__construct($prefix);
}
/**
* {@inheritdoc}
*/
protected function extractRoles(TokenInterface $token)
{
return $this->roleHierarchy->getReachableRoles($token->getRoles());
}
}
Run Code Online (Sandbox Code Playgroud)
getReachableRoles方法返回用户可以使用的所有角色.例如:
ROLE_ADMIN
/ \
ROLE_SUPERVISIOR ROLE_BLA
| |
ROLE_BRANCH ROLE_BLA2
|
ROLE_EMP
or in Yaml:
ROLE_ADMIN: [ ROLE_SUPERVISIOR, ROLE_BLA ]
ROLE_SUPERVISIOR: [ ROLE_BRANCH ]
ROLE_BLA: [ ROLE_BLA2 ]
Run Code Online (Sandbox Code Playgroud)
如果用户分配了ROLE_SUPERVISOR角色,则Method返回角色ROLE_SUPERVISOR,ROLE_BRANCH和ROLE_EMP(角色对象或类,实现RoleInterface)
此外,如果没有定义RoleHierarchy,则将禁用此自定义选民 security.yaml
private function createRoleHierarchy($config, ContainerBuilder $container)
{
if (!isset($config['role_hierarchy'])) {
$container->removeDefinition('security.access.role_hierarchy_voter');
return;
}
$container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']);
$container->removeDefinition('security.access.simple_role_voter');
}
Run Code Online (Sandbox Code Playgroud)
为了解决我的问题,我创建了自己的自定义选民,并扩展了RoleVoter-Class:
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Acme\Foundation\UserBundle\Entity\Group;
use Doctrine\ORM\EntityManager;
class RoleHierarchyVoter extends RoleVoter {
private $em;
public function __construct(EntityManager $em, $prefix = 'ROLE_') {
$this->em = $em;
parent::__construct($prefix);
}
/**
* {@inheritdoc}
*/
protected function extractRoles(TokenInterface $token) {
$group = $token->getUser()->getGroup();
return $this->getReachableRoles($group);
}
public function getReachableRoles(Group $group, &$groups = array()) {
$groups[] = $group;
$children = $this->em->getRepository('AcmeFoundationUserBundle:Group')->createQueryBuilder('g')
->where('g.parent = :group')
->setParameter('group', $group->getId())
->getQuery()
->getResult();
foreach($children as $child) {
$this->getReachableRoles($child, $groups);
}
return $groups;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我的设置类似于zls.我对角色的定义(在我的例子中,我称之为组):
Acme\Foundation\UserBundle\Entity\Group:
type: entity
table: sec_groups
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 50
role:
type: string
length: 20
manyToOne:
parent:
targetEntity: Group
Run Code Online (Sandbox Code Playgroud)
而userdefinition:
Acme\Foundation\UserBundle\Entity\User:
type: entity
table: sec_users
repositoryClass: Acme\Foundation\UserBundle\Entity\UserRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
username:
type: string
length: 30
salt:
type: string
length: 32
password:
type: string
length: 100
isActive:
type: boolean
column: is_active
manyToOne:
group:
targetEntity: Group
joinColumn:
name: group_id
referencedColumnName: id
nullable: false
Run Code Online (Sandbox Code Playgroud)
也许这有助于某人.