authority-php/authority

一个简单且灵活的PHP授权系统

2.2.2 2015-05-16 10:35 UTC

This package is auto-updated.

Last update: 2024-09-20 00:27:17 UTC


README

一个简单且灵活的基于活动/资源的PHP授权系统

Build Status

通过Composer安装

将Authority添加到composer.json文件中,以要求Authority

"require" : {
    "authority-php/authority": "dev-master"
}

然后通过composer安装

composer install

更详细的安装信息可在docs/install.md中找到

简介

Authority是一个专注于活动和资源概念的PHP授权系统,而不是角色。使用不同的用户角色仍然完全可能且通常需要,但Authority允许您简单地检查用户是否被允许在给定的资源或活动上执行操作,而不是在您的整个应用程序中基于角色来确定功能。

让我们以编辑一个Post $post 为例。

首先,我们将使用标准的基于角色的授权检查来检查可能能够删除帖子的角色

if ($user->hasRole('admin') || $user->hasRole('moderator') || $user->hasRole('editor')) {
    // Can perform actions on resource
    $post->delete();
}

虽然这确实有效,但它非常容易需要更改,并且随着角色的增加可能会变得相当庞大。

让我们看看简单地检查资源上的活动会怎样。

if ($authority->can('edit', $post)) {
    // Can perform actions on resource
    $post->delete();
}

我们不需要在代码库中添加关于用户角色的多个条件,我们只需要编写一个条件,类似于“如果当前用户可以编辑这篇帖子”。

默认行为

以下是Authority的两个重要默认行为,请记住

  1. 未指定的规则被拒绝 - 如果您检查尚未设置的规则,Authority将拒绝该活动。
  2. 规则按声明顺序评估 - 最后一个规则具有优先权。

基本用法

Authority旨在每个应用程序中实例化一次(尽管支持多个实例)。它与支持单例访问的IoC(控制反转)容器配合良好,如Laravel的IoC,或通过使用标准依赖注入。您可以在应用程序授权资源之前分配规则,或者随时添加。

Authority构造函数至少需要一个参数 - 代表当前用户的对象。我们稍后会介绍第二个可选参数。

<?php

use Authority\Authority;

// Assuming you have your current user stored
// in $currentUser, with the id property of 1
$authority = new Authority($currentUser);

/*
    * Let's assign an alias to represent a group of actions
    * so that we don't have to handle each action individually each time
    */
$authority->addAlias('manage', ['create', 'update', 'index', 'read', 'delete']);

// Let's allow a User to see all other User resources
$authority->allow('read', 'User');

/*
    * Now let's restrict a User to managing only hiself or herself through
    * the use of a conditional callback.
    *
    * Callback Parameters:
    * $self is always the current instance of Authority so that we always
    * have access to the user or other functions within the scope of the callback.
    * $user here will represent the User object we'll pass into the can() method later
    */
$authority->allow('manage', 'User', function($self, $user) {
    // Here we'll compare id's of the user objects - if they match, permission will
    // be granted, else it will be denied.
    return $self->user()->id === $user->id;
});

// Now we can check to see if our rules are configured properly

$otherUser = (object) ['id' => 2];
if ($authority->can('read', 'User')) {
    echo 'I can read about any user based on class!';
}

if ($authority->can('read', $otherUser)) {
    echo 'I can read about another user!';
}

if ($authority->can('delete', $otherUser)) {
    echo 'I cannot edit this user so you will not see me :(';
}

if ($authority->can('delete', $user)) {
    echo 'I can delete my own user, so you see me :)';
}

如果我们运行上述脚本,我们将看到

I can read about any user based on class!
I can read about another user!
I can delete my own user, so you see me :)

中级用法

即将推出

高级用法

即将推出