5

我正在使用 BjyAuthorize 和 Zend Framework2 来实现授权,并且能够成功地集成来自数据库的角色。现在我也想从数据库表中获取我的规则和守卫。我怎样才能做到这一点?

4

2 回答 2

7

这里最简单的方法和“诀窍”实际上是:

  1. 将您的规则和防护设置为与示例配置中显示的相同的数组格式。因此,在从数据库中读取记录后,无论原始数据库数据采用何种格式,都要对其进行处理以匹配与配置中相同的保护格式。(我的回答详细介绍了如何使用 Doctrine ORM 做到这一点,但也应该让您对其他数据库引擎有所了解。只需用您最喜欢的数据库引擎替换“数据库读取”操作)

  2. 将已经采用 BjyAuthorize 期望的正确格式的规则(因为您已经这样做了)注入到您将编写BjyAuthorize\Guard\Controller的 , from inside 中。YOUR_MODULE_NAME\Factory\DoctrineControllerGuardAdapterFactoryBjy 的控制器会将规则视为来自配置*,并且不会怀疑有任何差异。

  3. 退后一步,享受吧!

这是您需要在自己的模块中编写的构造:

namespace YOUR_MODULE_NAME\Factory;

/**
 * See "How and where exactly to register the factory" in ZF2 config
 * below in my answer.
 */
class [Custom]ControllerGuardAdapterFactory 
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /**
         * Retrieve your rules from favorive DB engine (or anything)
         *
         * (You may use $serviceLocator to get config for you DB engine)
         * (You may use $serviceLocator to get your DB engine)
         * (You may use $serviceLocator to get ORM Entity for your DB engine)
         * (Or you may hack your DB connection and retrieval in some other way)
         *
         * Hell, you may read them from a text file using PHP's file() method
         * and not use $serviceLocator at all
         *
         * You may hardcode the rules yourself right here for all that matters
         */            
        $rules = ... //array(...);


        /** 
         * Inject them into Bjy's Controller
         *
         * Rules must be in the same format as in Bjy config, or it will puke.
         * See how ['guards'][\BjyAuthorize\Guard\Controller::class] is constructed 
         * in Bjy configuration for an example
         */             
        return new \BjyAuthorize\Guard\Controller($rules, $serviceLocator); 
    }
}

现在观察并观察这会变得多么令人麻木!(仿照 ​​Bjy 自己的机制)

这主要是 ZF2、OO 和 Bjy “配置地狱”,伙计们,除此之外没什么特别的。欢迎来到 ZF2 和 Bjy 和 ORM 配置地狱。不客气。

详细解答 - 如何实施?

编写一个适配器工厂,它从数据库中读取规则,然后将它们注入到BjyAuthorize 的 Controller Guard中。效果将与读取规则相同['guards'][\BjyAuthorize\Guard\Controller::class]

什么?

BjyAuthorize 的 Controller Guard 的工作方式是采用某种格式(为 指定的格式['guards']['BjyAuthorize\Guard\Controller'])的规则,然后使用这些规则填充 ACL。它还为您从规则中计算资源并将其加载到 ACL 中。如果没有,您将不得不编写自己的资源提供程序来执行此操作。

所以任务变成了:

  • 从数据库加载规则并将规则转换为 BjyAuthorize 期望的格式。这可以在您自己的规则提供程序中完成,就像这个一样
  • 您可以使用工厂从 module.config.php 文件中加载特定的数据库和存储类配置数组。我把我的放在下面['guards']['YOUR_MODULE_NAME_controller_guard_adapter']
'guards' => array(
        'YOUR_MODULE_NAME_controller_guard_adapter' => array(
            'object_manager' => 'doctrine.entity_manager.orm_default',
            'rule_entity_class' => 'YOUR_MODULE_NAME\Entity\ObjectRepositoryProvider'
        )
)
  • (续)我把它放在守卫之下,而不是 rule_providers,因为我们在这里处理的不是纯粹的规则提供者。它是一个保护提供者,或“一个从 ObjectRepositoryProvider 中获取规则并将它们注入控制器保护的适配器”。 这个工厂应该和 this 类似,除了你将加载规则,而不是角色。然后,您将在下一步中将规则注入到 Controller 中。
  • 将规则注入到Controller中,很像这里做的

示例实施细节(来自评论中的 Q/A)

更多关于“将规则注入控制器”的最后一点。基本上两个步骤:1)确保您已经(或将)以某种方式生成规则(这是困难的一步)。2)将这些规则注入控制器(这是更简单的步骤)。实际的注入是这样完成的

$rules = __MAGIC__;  //get rules out of somewhere, somehow.
return new Controller($rules, $serviceLocator); //$rules injection point

有关我自己的实现,请参见下面的代码块,其中块中的最后一行是我在上面给出的行。

namespace YOUR_MODULE_NAME\Factory;

use BjyAuthorize\Exception\InvalidArgumentException;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use YOUR_MODULE_NAME\Provider\Rule\DoctrineRuleProvider;    //this one's your own
use BjyAuthorize\Guard\Controller;

class DoctrineControllerGuardAdapterFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        //just setting up our config, move along move along...
        $config = $serviceLocator->get('Config');
        $config = $config['bjyauthorize'];

        //making sure we have proper entries in our config... 
        //move along "nothing to see" here....
        if (! isset($config['guards']['YOUR_MODULE_NAME_controller_guard_adapter'])) {
            throw new InvalidArgumentException(
                'Config for "YOUR_MODULE_NAME_controller_guard_adapter" not set'
            );
        }

        //yep all is well we load our own module config here
        $providerConfig = $config['guards']['YOUR_MODULE_NAME_controller_guard_adapter'];

        //more specific checks on config
        if (! isset($providerConfig['rule_entity_class'])) {
            throw new InvalidArgumentException('rule_entity_class not set in the YOUR_MODULE_NAME guards config.');
        }

        if (! isset($providerConfig['object_manager'])) {
            throw new InvalidArgumentException('object_manager not set in the YOUR_MODULE_NAME guards config.');
        }

        /* @var $objectManager \Doctrine\Common\Persistence\ObjectManager */
        $objectManager = $serviceLocator->get($providerConfig['object_manager']);

        //orp -- object repository provider
        //here we get our class that preps the object repository for us
        $orp=new DoctrineRuleProvider($objectManager->getRepository($providerConfig['rule_entity_class']));

        //here we pull the rules out of that object we've created above
        //rules are in the same format BjyAuthorize expects
        $rules=$orp->getRules();

        //here pass our rules to BjyAuthorize's own Guard Controller.  
        //It will not know the difference if we got the rules from Config or from Doctrine or elsewhere,  
        //as long as $rules are in the form it expects.
        return new Controller($rules, $serviceLocator); 
    }
}

教义规则提供者

namespace YOUR_MODULE_NAME\Provider\Rule;

use Doctrine\Common\Persistence\ObjectRepository;
use BjyAuthorize\Provider\Rule\ProviderInterface;

/**
 * Guard provider based on a {@see \Doctrine\Common\Persistence\ObjectRepository}
 */
class DoctrineRuleProvider implements ProviderInterface
{
    /**
     * @var \Doctrine\Common\Persistence\ObjectRepository
     */
    protected $objectRepository;

    /**
     * @param \Doctrine\Common\Persistence\ObjectRepository $objectRepository            
     */
    public function __construct(ObjectRepository $objectRepository)
    {
        $this->objectRepository = $objectRepository;
    }

    /**
     * Here we read rules from DB and put them into an a form that BjyAuthorize's Controller.php understands
     */
    public function getRules()
    {
        //read from object store a set of (role, controller, action) 
        $result = $this->objectRepository->findAll();

        //transform to object BjyAuthorize will understand
        $rules = array();
        foreach ($result as $key => $rule)
        {
            $role=$rule->getRole();
            $controller=$rule->getController();
            $action=$rule->getAction();            

            if ($action==='all')    //action is ommitted
            {
                $rules[$controller]['roles'][] = $role;
                $rules[$controller]['controller'] = array($controller);
            }
            else
            {
                $rules[$controller.':'.$action]['roles'][]=$role;
                $rules[$controller.':'.$action]['controller']=array($controller);
                $rules[$controller.':'.$action]['action']=array($action);
            }                       
        }    

        return array_values($rules);
    }
}

问:如何以及在哪里注册工厂DoctrineControllerGuardAdapterFactory

A:试试这条路: module\YOUR_MODULE_NAME\config\module.config.php并且有

'service_manager' => array(
    'factories' => array(
        'YOUR_MODULE_NAME_controller_guard_adapter' => \YOUR_MODULE_NAME\Factory\DoctrineControllerGuardAdapterFactory::class
    )
)
  • 注意: YOUR_MODULE_NAME。符号左边的东西=>是“钥匙”,可以是你想要的任何东西。Bjy 中的约定是它类似于实际的类名和路径。右侧的=>内容是您要使用此键调用的类的实际完全限定名称空间。
于 2014-01-17T23:00:22.300 回答
1

基本上你必须编写自己的Provider.

查看不同的RoleProvider. 每个RoleProvider实现Provider\Role\ProviderInterface. 当您想要实施 Guards 和 Rules 时,也必须做同样的事情。您进入特定目录Provider\RuleProvider\Resource检查特定的ProviderInterface.

这样您就可以编写自己的类来实现接口,然后通过配置告诉 BjyAuthorize 使用您的提供程序类。

就 Guards 而言,我相信还不能从数据库中创建它们。您必须修改/ PR 模块本身才能做到这一点。

于 2013-08-16T06:44:15.960 回答