psecio / propauth-provider
为Blade模板添加PropAuth检查功能的Laravel提供者
0.1
2015-10-22 12:13 UTC
Requires
- php: >=5.5.0
- psecio/propauth: >=0.9
Requires (Dev)
- phpunit/phpunit: 4.1.4
This package is auto-updated.
Last update: 2024-09-15 10:45:45 UTC
README
此服务提供者(基于Laravel 5+的应用程序),引入了对当前用户执行PropAuth评估检查的功能,以与预定义的策略进行比较。
用法
要使用此提供者,更新您的Laravel应用程序的app.php
配置文件中的“providers”部分以包含此提供者
<?php 'providers' => [ /* other providers */ \Psecio\PropAuth\PolicyTemplateServiceProvider::class, ] ?>
还需要什么
此库需要以下两项:
- 您已安装PropAuth功能
- 您已根据此设置在应用程序中定义了策略: 使用PropAuth在Laravel中进行安全策略评估
本质上,要求是存在另一个服务提供者(例如,在示例中是PolicyServiceProvider
),该服务提供者在名为“policies”的单例中定义您的策略并返回一个执行器对象。例如,您可以在app/providers/PolicyServiceProvider.php
中放入以下内容
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Psecio\PropAuth\Enforcer; use Psecio\PropAuth\Policy; use Psecio\PropAuth\PolicySet; class PolicyServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('policies', function($app) { $set = PolicySet::instance() ->add('can-edit', Policy::instance()->hasUsername('ccornutt')) ); return Enforcer::instance($set); }); } } ?>
这仅仅定义了一个策略,can-edit
,它检查当前用户(通过\Auth::user()
获取)是否有“username”属性为“ccornutt”。有了这个,您就可以使用此存储库中的服务提供者来向Blade模板添加检查。
例如,要使用上面的can-edit
检查,您可以使用以下内容
@allows('can-edit')
they can edit!
@endallows
@denies('can-edit')
they're denied being able to edit
@enddenies
公开的两个方法是@allows
和@denies
,它们需要一个必选参数。如果您使用闭包处理更复杂的PropAuth
检查,还可以传递可选参数。因此,如果您的策略定义如下
<?php $this->app->singleton('policies', function($app) { $set = PolicySet::instance() ->add('can-delete', Policy::instance()->can(function($subject, $post) { return $post->author == 'ccornutt'; }) ); return Enforcer::instance($set); }); ?>
您需要传递一个值/对象给$post
在can-delete
闭包中。您可以通过为@allows
/@denies
提供更多可选参数来实现这一点
@allows('can-delete', $post)
Can delete this post because the username on the post is "ccornutt"
@endallows