Symfony中的动态角色 [英] Dynamic roles in symfony

查看:50
本文介绍了Symfony中的动态角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试为应用程序中的用户分配动态角色.我尝试使用事件监听器来执行此操作,但它只是为该一个HTTP请求添加了动态角色.

I have been trying to assign dynamic roles to users in my application. I tried to use an event listener to do that, but it just added the dynamic role for that one http request.

这是我的自定义事件侦听器中的添加角色的函数.

This is the function in my custom event listener that adds the role.

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {

    $user = $this->security->getToken()->getUser();

    $role = new Role;
    $role->setId('ROLE_NEW');
    $user->addRole($role);
}

但是我不确定事件监听器是否可能做到这一点.我只需要找到一种很好的方法来在用户登录的整个过程中添加角色.我将不胜感激.

But I am not sure if this is even possible to do with event listeners. I just need to find a nice way how to add the roles for the whole time the user is logged. I would appreciate any help and suggestions.

推荐答案

我还没有对此进行测试,但是阅读食谱可能会起作用.

I haven't tested this yet, but reading the cookbook this could work.

此示例是本食谱中示例的修改版本,可满足您的要求.

This example is a modified version of the example in the cookbook to accomodate for your requirements.

class DynamicRoleRequestListener
{
    public function __construct($session, $security)
    {
        $this->session = $session;
        $this->security = $security;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            // don't do anything if it's not the master request
            return;
        }

        if ($this->session->has('_is_dynamic_role_auth') && $this->session->get('_is_dynamic_role_auth') === true) {
            $role = new Role("ROLE_NEW"); //I'm assuming this implements RoleInterface
            $this->security->getRoles()[] = $role; //You might have to add credentials, too.
            $this->security->getUser()->addRole($role);
        }

        // ...
    }

    private $session;
    private $security;
}

然后将其声明为服务.

services:
    kernel.listener.dynamicrolerequest:
        class: Your\DemoBundle\EventListener\DynamicRoleRequestListener
        arguments: [@session, @security.context]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

类似的问题在这里:如何在使用symfony2(和fosUserBundle)登录后动态添加用户角色?

这篇关于Symfony中的动态角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆