Symfony2,奏鸣曲。无需注销即可更新角色

时间:2014-10-23 10:45:36

标签: symfony sonata-admin user-roles

需要在不注销的情况下更新用户的角色。我使用的是sonata admin bundle:

class CompanyAdmin extends Admin
{
...
public function postPersist($company)
    {       
        $this->checkCompanyAdmin($company);
    }
...
protected function checkCompanyAdmin($company){
        $companyAdmins = $company->getCompanyAdmins();
        if($companyAdmins) {
            $companyDefaultGroup = $company->getDefaultGroup();
            foreach ($companyAdmins as $ca) {
                $ca->addRole('ROLE_COMPANY_'.$company->getId().'_ADMIN');
                $ca->addRole('ROLE_PARTNER');
                $ca->setCompany($company);          
                //***
                if($companyDefaultGroup) {
                    $ca->addGroup($companyDefaultGroup);
                }
            }
        }
        $this->em->flush();
    }   
...

帮助我在不注销的情况下升级角色。

1 个答案:

答案 0 :(得分:0)

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($ca,null,'main',$ca->getRoles());
$this->getConfigurationPool()->getContainer()->get('security.context')->setToken($token);
$this->getConfigurationPool()->getContainer()->get('fos_user.user_manager')->refreshUser($ca);

仅当$ ca == $ this-> getUser()

时,它才有效

在securirty.yml中添加的正确变体: 安全:     always_authenticate_before_granting:true