备件/监管者

基于属性的授权管理器。

v0.1.1 2019-09-17 12:22 UTC

This package is auto-updated.

Last update: 2024-09-18 18:43:51 UTC


README

基于动作的授权管理器

快速免责声明:这基本上是一个进行中的工作。目前这更像是一个“概念验证”,而不是可工作的代码。尽管逻辑是合理的,我完全有意图将其完成为一个出色的1.0版本。

Build Status Scrutinizer Code Quality Build Status Code Coverage

这是什么?为什么我应该关心?

Overseer是一个“基于动作”的授权管理器,这意味着它基于授权给定的“主体”(如文章、产品、类别等)的“动作”(如读取、编辑、删除等)。

Overseer专注于将授权逻辑与应用程序的其他部分解耦。当解决“该产品的所有者可以编辑它”的问题时,其他授权管理器往往会直接将逻辑编织到该产品类中,或者将所有可能的行为(读取、写入、删除等)堆叠到一个大方法中。不管怎样,它都会破坏SOLID原则(单一职责原则),这就是Overseer介入的地方。

Overseer的基本构建块是“投票机构”,由“投票者”组成。每个动作和主体的组合都可以有自己的投票机构(尽管不一定要有),从而分离出相关的关注点和责任。

安装

Composer

就是这样,伙计们。

composer require spareparts/overseer

基本用法

让我们假设我们有一个文章网站,我们想要确保管理员始终可以读取文章,而作者只能在未被禁止的情况下才能读取。

这就是我们为这个特定主题和动作创建投票机构的方式。它包含四个投票者,

$assembly = new VotingAssembly(
	$subjectName = 'article',
	$actionName = 'read',
	$strategy = StrategyEnum::FIRST_VOTE_DECIDES(),
	$voters = [
		new RoleVoter(VotingDecisionEnum::ALLOWED(), 'admin'),
		new ClosureVoter(function (DummyArticle $article, IdentityContext $context) {
			// allow the owner to edit
			if ($subject->ownerId === $context->getId()) {
				return new SingleVoterResult(VotingDecisionEnum::ALLOWED());
			}
			return null;
		}),
		new ClosureVoter(function (DummyArticle $article) {
			// deny access if the article is banned
			if ($subject->isBanned()) {
				return new SingleVoterResult(VotingDecisionEnum::ALLOWED());
			}
			return null;
		}),
		new RoleVoter(VotingDecisionEnum::ALLOWED(), 'user'),
	]
);

$authorizationManager = new GenericVotingManager([
	// our article edit assembly
	$assembly,
	// other assemblies...
	// ...
]);

现在让我们使用它

$context = new IdentityContext($userId, $userRoles);
$authorized = $authorizationManager->vote('edit', $article, $context);
if ($authorized->getDecision() === VotingDecisionEnum::ALLOWED()) {
	// we can edit!
}