dsgfdgh14569 2019-07-05 12:34
浏览 113

有没有办法从Symfony中具有特定子角色的用户中删除所有角色?

I am using the FosUserBundle which provides the function where you can remove roles.

$user->removeRole("ROLE_SUBSCRIBER_BASIC")

This is nice and all, but my main problem is that I would like to remove the role by a specific subrole. My hierarchy in security.yml looks like this:

    ROLE_SUBSCRIBER: ROLE_USER
    ROLE_SUBSCRIBER_MONTHLY: [ROLE_SUBSCRIBER]
    ROLE_SUBSCRIBER_YEARLY: [ROLE_SUBSCRIBER]
    ROLE_SUBSCRIBER_BASIC:  [ROLE_SUBSCRIBER]
    ROLE_PRIVILEGE_PLUS: [ROLE_SUBSCRIBER]
    ROLE_SUBSCRIBER_PLUS:  [ROLE_PRIVILEGE_PLUS]
    ROLE_SUBSCRIBER_EXTRA:  [ROLE_PRIVILEGE_PLUS]

As you can see a PLUS, EXTRA and BASIC subscriber all are subscribers so i gave them a subrole "ROLE_SUBSCRIBER". In my unsubscribe function, I would like to remove the current subscriber role, without having to use if else loops like this:

 public function unsubscribe(User $user)
    {
    if($user->hasRole("ROLE_SUBSCRIBER_BASIC")){
        $user->removeRole("ROLE_SUBSCRIBER_BASIC");
    }
    if($user->hasRole("ROLE_SUBSCRIBER_PLUS")){
        $user->removeRole("ROLE_SUBSCRIBER_PLUS");
    }
    if($user->hasRole("ROLE_SUBSCRIBER_EXTRA")){
        $user->removeRole("ROLE_SUBSCRIBER_EXTRA");
    }

... }

This if/else loops does its job, but think about the future. What if my boss wants there to be more subscriber roles, then I would have to edit this function every single time and add another IF. Is there a more efficient way to do this? Like by deleting the role by subrole.

$user->removeRole("ROLE_SUBSCRIBER")

This way it would remove ROLE_SUBSCRIBER_EXTRA,ROLE_SUBSCRIBER_BASIC, ...MONTHLY, ...YEARLY or ...PLUS automatically, without me having to check what kind of subscription the user currently has!?

  • 写回答

1条回答 默认 最新

  • douhui8454 2019-07-05 13:29
    关注

    You can do something like this:

    const KEEP_ROLES = ['ROLE_ADMIN'];
    
    $rolesToRemove = array_diff($user->getRoles(), KEEP_ROLES);
    
    foreach ($rolesToRemove as $role) {
       $user->removeRole($role);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?