我想将经过身份验证的用户角色列表传递到我的前端应用程序,以便我可以在前端和后端使用相同的访问控制结构。
我正在查找安全/身份验证类,因为这是 isGranted 函数让我执行此操作的地方
$this->container->get('security.context')->isGranted('ROLE_SUPER_ADMIN')
但是我找不到任何内容来获取角色列表,这不是受支持的功能吗?
nb:我不需要整个角色层次结构,只需要经过身份验证的用户的角色列表
最佳答案
我最终添加了一个新的存储库函数和一个服务方法来获取此信息。
MyProject/UserBundle/Entity/Repository/UserRepository
public function getRoles($userId)
{
$queryBuilder = $this->createQueryBuilder('u');
$queryBuilder
->select('u.id, u.roles AS user_roles, g.roles AS group_roles')
->leftJoin('u.groups', 'g')
->andWhere('u.id = :user_id')
->setParameter('user_id', $userId);
return $queryBuilder->getQuery()->getArrayResult();
}
MyProject/UserBundle/Service/UserService
public function getUserRoles($user)
{
$groupRoles = $this->repository->getRoles($user->getId());
$roles = array('user_roles' => array(), 'group_roles' => array());
foreach ($groupRoles as $groupRole) {
$roles['user_roles'] = array_merge($roles['user_roles'], $groupRole['user_roles']);
$roles['group_roles'] = array_merge($roles['group_roles'], $groupRole['group_roles']);
}
return $roles;
}
这给了我一个像这样的数组
"roles":{
"user_roles":[],
"group_roles":["ROLE_ADMIN","ROLE_ONE","ROLE_TWO","ROLE_BEST"]
}
关于symfony - 在 Symfony2 中如何获取用户的完整角色列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39478481/