symfony2:使用 isGranted 检查用户权限

symfony2: check user permission with isGranted

在class vendor\friendsofsymfony\user-bundle\Model\User.php据说

/**
 * Never use this to check if this user has access to anything!
 *
 * Use the SecurityContext, or an implementation of AccessDecisionManager
 * instead, e.g.
 *
 *         $securityContext->isGranted('ROLE_USER');
 *
 * @param string $role
 *
 * @return boolean
 */
public function hasRole($role)
{
    return in_array(strtoupper($role), $this->getRoles(), true);
}

但被授予 return 实际用户的角色

        $data = $form->getData();
        $user = new User();
        $user->setUsername($data->getUsername());
        $user->setExpiresAt($data->getExpiresAt());
        $user->setName($data->getName());
        $user->setPassword($data->getPassword());
        $user->setEmail($data->getEmail());
        $user->setCredentialsExpired($data->isCredentialsExpired());
        $user->setRoles(array('ROLE_NEW'));
        $em->persist($user);
        $em->flush();
        // return false
        var_dump(
        $this->get('security.context')>isGranted('ROLE_NEW',$user));

如何查看特定用户的 "isGranted"?

编辑:我可能误读了你的问题。如果您想检查特定用户的权限,请参阅此处:Check if a role is granted for a specific user in Symfony2 ACL


原回答

您应该首先使用 FOSUserBundle 提供的 UserManager 获取要检查的特定用户的实例。然后您可以检查该特定用户的 isGranted。

您可以使用,例如:

$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserByUsername('foobar'));

source 中,您可能会找到几种查找用户的方法,包括通用的 findUserBy()

您使用的是哪个版本?。在最新版本中,您必须这样做:

 if ($this->get('security.authorization_checker')-isGranted('ROLE_NEW'))

简单地说:

// $specific_user = get specific user from db.
if (in_array('ROLE_SPECIFIC_ROLE', $specific_user->getRoles()))
{
    // Make specific operation on specific user
}