foothing/laravel-lock-routes

为 Laravel Lock 权限添加基于路由的检查。

0.3.0 2017-06-23 16:34 UTC

This package is auto-updated.

Last update: 2024-09-22 23:24:31 UTC


README

这是一个 Laravel 5 包,允许将 Lock 权限绑定到路由上。

它实现了 Laravel WrapprLock 提供者。

安装

composer require foothing/laravel-lock-routes

设置

在您的 config/app.php 提供者数组中添加 Wrappr 服务提供者。

'providers' => [
	// ...
	Foothing\Wrappr\WrapprServiceProvider::class
]

发布包配置和迁移文件

php artisan vendor:publish --provider="Foothing\Wrappr\WrapprServiceProvider"

更新您的 config/wrappr.php

'permissionsProvider' => 'Foothing\Wrappr\Lock\LockProvider',
'usersProvider' => 'Foothing\Wrappr\Providers\Users\DefaultProvider',

中间件

有两种中间件用例。您可以在 Laravel 路由器中使用它,也可以与复杂模式路由一起使用。更多信息请参阅 Wrappr 文档

启用 Laravel 路由器中间件

protected $routeMiddleware = [
	'wrappr.check' => 'Foothing\Wrappr\Middleware\CheckRoute',
];

使用 routes.php 中的 CheckRoute 中间件来控制对您路由的访问,如下所示

Route::get('api/users', ['middleware:wrappr.check:admin.users', function() {
	// Access is allowed for the users with the 'admin.users' permission
}]);

CheckRoute 中间件接受 3 个参数

  • 所需的权限
  • 可选的资源名称,例如 'user' (可选)
  • 可选的资源标识符(整数)

示例

Route::get('api/users/{id?}', ['middleware:wrappr.check:read.users,user,1', function() {
	// Access is allowed for the users with the 'read.users' permission on
	// the 'user' resource with the {id} identifier
}]);

此外,中间件还可以处理您的路由参数。考虑以下情况

Route::get('api/users/{id?}', ['middleware:wrappr.check:read.users,user,{id}', function() {
	// Access is allowed for the users with the 'read.users' permission on
	// the 'user' resource with the {id} identifier
}]);

当您在括号内传递资源标识符时,中间件将尝试自动从 HTTP 请求中检索该值。

启用自定义路由中间件

当您无法在路由定义级别进行精确控制时,有另一种处理权限的方法。考虑以下全局 RESTful 控制器

Route::controller('api/v1/{args?}', 'FooController');

假设您的控制器使用变量模式处理路由,例如以下示例

GET /api/v1/resources/users
GET /api/v1/resources/posts
POST /api/v1/services/publish/post

在这种情况下,您无法使用先前的方法绑定权限,所以 CheckPath 中间件就派上用场了。为了启用此行为,您需要执行一些额外的设置步骤。

将全局中间件添加到您的 App\Http\Kernel 中,如下所示

protected $middleware = [
	\Foothing\Wrappr\Middleware\CheckPath::class
];

现在您可以在配置文件中配置您的路由,或者按照 Wrappr 路由文档 以编程方式执行。

ACL 抽象层

如果您希望与您的应用程序和 acl 库(在这个例子中是 Lock)更解耦,您可以使用在提供者中实现的 acl 操作方法。请参阅以下示例

$this->provider = \App::make('Foothing\Wrappr\Providers\Permissions\PermissionProviderInterface');

// Returns all the user's permissions
$this->provider->user($user)->all();

// Returns all the role's permissions
$this->provider->role('admin')->all();

// Allow the user to edit post with id = 1
$this->provider->user($user)->grant('edit', 'post', 1);

// Revoke previous permission
$this->provider->user($user)->revoke('edit', 'post', 1);

// Return false.
$this->provider->check($user, 'edit', 'post', 1);

许可证

MIT