wishfoundry/authorize

适用于 Laravel 4 的身份验证和授权包

dev-master 2013-04-10 06:03 UTC

This package is not auto-updated.

Last update: 2024-09-28 13:52:23 UTC


README

Authorize 是知名 Authority 库(由 Matthew Machuga 和 Jesse O'brien 开发)的 Laravel 4 版本。大多数功能类似,但有所增强。此库通过赋予系统 Auth 类超级能力来修复它,并旨在验证当前系统用户的身份验证和权限。

!docs Authorize

Rommie:需要文档吗?

安装

此包依赖于 php5.4 高级闭包。不支持 php5.3,也不会支持。要安装,请在 composer.json 文件中添加包依赖

"wishfoundry/authorize": "dev-master"

并在您的 app/config/app.php 文件中替换默认的认证服务提供者

#'Illuminate\Auth\AuthServiceProvider',
'Wishfoundry\Authorize\AuthorizeServiceProvider',

迁移

在 src/migrations 中提供了一个示例迁移,但不是必需的。请根据需要自定义。还提供了一个示例 trait,供您在用户模型中使用。只需包含

class User {
....
use Wishfoundry\Authorize\AuthorizeUserRoleTrait;
}

或根据需要自定义。

规则

Authorize 默认不包含规则。规则可以随时动态添加,从而节省不必要的数据库调用。添加规则的推荐方法是设置路由过滤器

在全局过滤器中,您可以设置一些基本别名

App::before(function($request)
{
	Auth::addAlias('Administrate', ['create', 'view', 'modify', 'delete', 'flag', 'unflag']);
	Auth::addAlias('Moderate',     ['view', 'delete', 'flag', 'unflag']);
	Auth::addAlias('AllButView',   ['create', 'modify', 'delete', 'flag', 'unflag']);
});

然后您可以在命名过滤器中定义您的规则

Route::filter('admin', function()
{
	if (Auth::guest())
	{
	    Auth::deny('AllButView', ['Post', 'Comment']);

	    /**
	     * Rule actions can be any arbitrary string you decide
	     * except for the reserved word all, which is defined internally
	     */
	    Auth::deny('all', 'User');
	}

    // Only make a DB call if user is logged in
	elseif (Auth::user()->hasRole('admin) )
	{
	    Auth::allow('Administrate', ['User', 'Post', 'Comment']);
	}
});

使用简单而优雅

if(Auth::can('delete', 'User')
{
    $user->delete()
}
...
if( Auth::cannot('view', 'Comment') )
{
    return Redirect::to('unauthorized');
}
// Or by aliases
if(Auth::can('Administrate', 'Post')) ...

对于更高级的使用,可以提供闭包

Auth::allow('delete', 'Post')->when(function($post){
    return $this->user()->id == $post->user_id;
});

它传递一个变量作为

if( Auth::can('delete', 'Post', $post) )
{
    $post->delete();
}