Laravel 快速添加身份验证和权限管理功能

阅读 (4789)
Laravel 快速添加身份验证和权限管理功能

如果您想快速向Laravel项目添加身份验证和授权,还可以访问https://auth0.com/overview查看Auth0的Laravel SDK和免费计划。 

此程序包允许您管理数据库中的用户权限和角色。

安装完成后,您可以执行以下操作:

// Adding permissions to a user
$user->givePermissionTo('edit articles');

// Adding permissions via a role
$user->assignRole('writer');

$role->givePermissionTo('edit articles');

如果您使用多个guard,我们也会为您提供保障。每个guard都有自己的一组权限和角色,可以分配给guard的用户。在自述文件的使用多重保护部分中阅读它。

因为所有权限都将在Laravel的门上注册,所以您可以测试用户是否拥有Laravel默认can功能的权限:

$user->can('edit articles');

安装框架 Installation

在 Laravel 安装

该软件包可用于Laravel 5.4或更高版本。如果您使用的是旧版本的Laravel,请查看此软件包的v1分支

您可以通过composer安装包:

composer require spatie/laravel-permission

在Laravel 5.5中,服务提供商将自动注册。在旧版本的框架中,只需在config/app.php文件中添加服务提供者:

'providers' => [
    // ...
    Spatie\Permission\PermissionServiceProvider::class,
];

您可以使用以下命令发布迁移

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

如果您正在为User模型使用UUID或GUID,则可以更新create_permission_tables.php迁移并替换$table->morphs('model')为:

$table->uuid('model_id');
$table->string('model_type');

发布迁移后,您可以通过运行迁移来创建角色表和权限表:

php artisan migrate

您可以使用以下命令发布配置文件:

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

发布后,该config/permission.php配置文件包含:

return [

    'models' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Eloquent model should be used to retrieve your permissions. Of course, it
         * is often just the "Permission" model but you may use whatever you like.
         *
         * The model you want to use as a Permission model needs to implement the
         * `Spatie\Permission\Contracts\Permission` contract.
         */

        'permission' => Spatie\Permission\Models\Permission::class,

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Eloquent model should be used to retrieve your roles. Of course, it
         * is often just the "Role" model but you may use whatever you like.
         *
         * The model you want to use as a Role model needs to implement the
         * `Spatie\Permission\Contracts\Role` contract.
         */

        'role' => Spatie\Permission\Models\Role::class,

    ],

    'table_names' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your roles. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'roles' => 'roles',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your permissions. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'permissions' => 'permissions',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your models permissions. We have chosen a
         * basic default value but you may easily change it to any table you like.
         */

        'model_has_permissions' => 'model_has_permissions',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your models roles. We have chosen a
         * basic default value but you may easily change it to any table you like.
         */

        'model_has_roles' => 'model_has_roles',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your roles permissions. We have chosen a
         * basic default value but you may easily change it to any table you like.
         */

        'role_has_permissions' => 'role_has_permissions',
    ],

    /*
     * By default all permissions will be cached for 24 hours unless a permission or
     * role is updated. Then the cache will be flushed immediately.
     */

    'cache_expiration_time' => 60 * 24,
    
    /*
     * When set to true, the required permission/role names are added to the exception
     * message. This could be considered an information leak in some contexts, so
     * the default setting is false here for optimum safety.
     */

    'display_permission_in_exception' => false,
];

在 Lumen 使用

您可以通过Composer安装软件包:

composer require spatie/laravel-permission

复制所需的文件:

cp vendor/spatie/laravel-permission/config/permission.php config/permission.php
cp vendor/spatie/laravel-permission/database/migrations/create_permission_tables.php.stub database/migrations/2018_01_01_000000_create_permission_tables.php

您还需要在其中创建另一个配置文件config/auth.php。在Laravel存储库中获取它或只运行以下命令:

curl -Ls https://raw.githubusercontent.com/laravel/lumen-framework/5.5/config/auth.php -o config/auth.php

然后,在bootstrap/app.php,注册中间件:

$app->routeMiddleware([
    'auth'       => App\Http\Middleware\Authenticate::class,
    'permission' => Spatie\Permission\Middlewares\PermissionMiddleware::class,
    'role'       => Spatie\Permission\Middlewares\RoleMiddleware::class,
]);

以及配置和服务提供商:

$app->configure('permission');
$app->register(Spatie\Permission\PermissionServiceProvider::class);

现在,运行 migrations:

php artisan migrate

用法 Usage

首先,将Spatie\Permission\Traits\HasRoles特征添加到User模型中:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ...
}

请注意,如果您需要使用HasRoles特征与另一个模型,例:Page您还需要添加protected $guard_name = 'web';才行,否则您将收到报错信息

use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasRoles;

class Page extends Model
{
   use HasRoles;

   protected $guard_name = 'web'; // or whatever guard you want to use

   // ...
}

此程序包允许用户与权限和角色相关联。每个角色都与多个权限相关联。A Role和a Permission是常规的Eloquent模型。他们需要一个name,可以像这样创建:

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);

可以使用以下方法之一为角色分配权限:

$role->givePermissionTo($permission);
$permission->assignRole($role);

可以使用以下方法之一将多个权限同步到角色:

$role->syncPermissions($permissions);
$permission->syncRoles($roles);

可以使用以下方法之一从角色中删除权限:

$role->revokePermissionTo($permission);
$permission->removeRole($role);

如果您使用多个防护,则还guard_name需要设置属性。在自述文件的使用多重保护部分中阅读它。

HasRoles特征为您的模型添加了Eloquent关系,可以直接访问或用作基本查询:

// get a list of all permissions directly assigned to the user
$permissions = $user->permissions;

// get all permissions inherited via the user's roles
$permissions = $user->getPermissionsViaRoles();

// get a collection of all defined roles
$roles = $user->getRoleNames(); // Returns a collection

HasRoles特性还增加了一个role范围,以供你的模型范围查询某些角色或权限:

$users = User::role('writer')->get(); // Returns only users with the role 'writer'

role范围可以接受一个字符串,一个\Spatie\Permission\Models\Role对象或一个\Illuminate\Support\Collection对象。

同样的特性还增加了一个范围,仅用于获得具有特定权限的用户。

$users = User::permission('edit articles')->get(); // Returns only users with the permission 'edit articles' (inherited or directly)

范围可以接受字符串,\Spatie\Permission\Models\Permission对象或\Illuminate\Support\Collection对象。

使用 "direct" 权限

请参阅下文同时使用角色和权限

可以向任何用户授予权限:

$user->givePermissionTo('edit articles');

// You can also give multiple permission at once
$user->givePermissionTo('edit articles', 'delete articles');

// You may also pass an array
$user->givePermissionTo(['edit articles', 'delete articles']);

可以从用户撤消权限:

$user->revokePermissionTo('edit articles');

或者一次撤销并添加新权限:

$user->syncPermissions(['edit articles', 'delete articles']);

您可以测试用户是否拥有权限:

$user->hasPermissionTo('edit articles');

或者您可以传递表示权限ID的整数

$user->hasPermissionTo('1');
$user->hasPermissionTo(Permission::find(1)->id);
$user->hasPermissionTo($somePermission->id);

您可以测试用户是否具有任何一组权限:

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

...或者如果用户拥有所有权限数组:

$user->hasAllPermissions(['edit articles', 'publish articles', 'unpublish articles']);

您还可以通过权限ID将整数传递给查找

$user->hasAnyPermission(['edit articles', 1, 5]);

保存的权限将在Illuminate\Auth\Access\Gate类中注册为默认保护。因此,您可以测试用户是否拥有Laravel默认can功能的权限:

$user->can('edit articles');

通过角色使用权限

可以将角色分配给任何用户:

$user->assignRole('writer');

// You can also assign multiple roles at once
$user->assignRole('writer', 'admin');
// or as an array
$user->assignRole(['writer', 'admin']);

可以从用户中删除角色:

$user->removeRole('writer');

角色也可以同步:

// All current roles will be removed from the user and replaced by the array given
$user->syncRoles(['writer', 'admin']);

您可以确定用户是否具有某个角色:

$user->hasRole('writer');

您还可以确定用户是否具有任何给定的角色列表:

$user->hasAnyRole(Role::all());

您还可以确定用户是否具有所有给定的角色列表:

$user->hasAllRoles(Role::all());

assignRolehasRolehasAnyRolehasAllRoles 和removeRole函数可以接受一个字符串,一个\Spatie\Permission\Models\Role对象或一个\Illuminate\Support\Collection对象。

可以为角色授予权限:

$role->givePermissionTo('edit articles');

您可以确定角色是否具有特定权限:

$role->hasPermissionTo('edit articles');

可以从角色撤消权限:

$role->revokePermissionTo('edit articles');

givePermissionTorevokePermissionTo函数可以接受字符串或Spatie\Permission\Models\Permission对象。

权限自动从角色继承。此外,还可以为用户分配单独的权限。例如:

$role = Role::findByName('writer');
$role->givePermissionTo('edit articles');

$user->assignRole('writer');

$user->givePermissionTo('delete articles');

在上面的示例中,角色被授予编辑文章的权限,并且该角色被分配给用户。现在,用户可以编辑文章并另外删除文章。“删除文章”的许可是用户的直接许可,因为它是直接分配给他们的。当我们这样调用时 $user->hasDirectPermission('delete articles')返回true,但 $user->hasDirectPermission('edit articles') 返回false 

如果构建用于为应用程序中的角色和用户设置权限的表单并希望限制或更改用户角色的继承权限,即允许仅更改用户的直接权限,则此方法很有用。

您可以列出所有这些权限:

// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;

// Permissions inherited from the user's roles
$user->getPermissionsViaRoles();

// All permissions which apply on the user (inherited and direct)
$user->getAllPermissions();

所有这些响应都是Spatie\Permission\Models\Permission对象的集合。

如果我们按照前面的示例,第一个响应将是具有delete article权限的集合,第二个响应将是具有权限的集合,edit article第三个响应将包含两者。

使用Blade指令

此软件包还添加了Blade指令,以验证当前登录的用户是否具有全部或任何给定的角色列表。

您可以选择传入guard将作为第二个参数执行检查的内容。

Blade 和 Roles

测试特定角色:

@role('writer')
    I am a writer!
@else
    I am not a writer...
@endrole

同上

@hasrole('writer')
    I am a writer!
@else
    I am not a writer...
@endhasrole

测试列表中的任何角色:

@hasanyrole($collectionOfRoles)
    I have one or more of these roles!
@else
    I have none of these roles...
@endhasanyrole
// or
@hasanyrole('writer|admin')
    I am either a writer or an admin or both!
@else
    I have none of these roles...
@endhasanyrole

测试所有角色:

@hasallroles($collectionOfRoles)
    I have all of these roles!
@else
    I do not have all of these roles...
@endhasallroles
// or
@hasallroles('writer|admin')
    I am both a writer and an admin!
@else
    I do not have all of these roles...
@endhasallroles

Blade 和 Permissions

此程序包不会添加任何特定于权限的Blade指令。相反,使用Laravel的本机@can指令来检查用户是否具有特定权限。

@can('edit articles')
  //
@endcan

或者

@if(auth()->user()->can('edit articles') && $some_other_condition)
  //
@endif

使用多个守卫 Using multiple guards

使用默认的Laravel auth配置时,所有上述方法都可以直接使用,无需额外配置。

但是,当使用多个防护时,它们将作为您的权限和角色的命名空间。这意味着每个守卫都有自己的一组权限和角色,可以分配给他们的用户模型。

使用具有多个守卫的权限和角色

创建新权限和角色时,如果未指定保护,则将使用配置数组中的第一个定义的保护auth.guards。为特定防护创建权限和角色时,您必须guard_name在模型上指定它们:

// Create a superadmin role for the admin users
$role = Role::create(['guard_name' => 'admin', 'name' => 'superadmin']);

// Define a `publish articles` permission for the admin users belonging to the admin guard
$permission = Permission::create(['guard_name' => 'admin', 'name' => 'publish articles']);

// Define a *different* `publish articles` permission for the regular users belonging to the web guard
$permission = Permission::create(['guard_name' => 'web', 'name' => 'publish articles']);

要检查用户是否拥有特定守卫的权限:

$user->hasPermissionTo('publish articles', 'admin');

注意:在确定角色/权限是否对给定模型有效时,它会按以下顺序选择保护:首先$guard_name是模型的属性; 然后配置中的守卫(通过提供商); 那么auth.guards配置数组中第一个定义的守卫; 然后是auth.defaults.guard配置。

分配权限和角色以保护用户

您可以使用相同的方法为用户分配权限和角色,如上所述通过角色使用权限。只需确保guard_name权限或角色与用户的保护匹配,否则GuardDoesNotMatch将引发异常。

在blade中判断角色

@role('super-admin', 'admin')
    I am a super-admin!
@else
    I am not a super-admin...
@endrole

使用中间件 Using a middleware

这个软件包附带RoleMiddlewarePermissionMiddleware中间件。您可以在app/Http/Kernel.php文件中添加它们。

protected $routeMiddleware = [
    // ...
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
    'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
];

然后,您可以使用中间件规则保护您的路由:

Route::group(['middleware' => ['role:super-admin']], function () {
    //
});

Route::group(['middleware' => ['permission:publish articles']], function () {
    //
});

Route::group(['middleware' => ['role:super-admin','permission:publish articles']], function () {
    //
});

或者,您可以使用|(管道)字符分隔多个角色或权限:

Route::group(['middleware' => ['role:super-admin|writer']], function () {
    //
});

Route::group(['middleware' => ['permission:publish articles|edit articles']], function () {
    //
});

您可以通过在构造函数中设置所需的中间件来类似地保护您的控制器:

public function __construct()
{
    $this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}

捕获角色和权限失败

如果要覆盖默认403响应,可以UnauthorizedException使用应用程序的异常处理程序:

public function render($request, Exception $exception)
{
    if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
        // Code here ...
    }

    return parent::render($request, $exception);
}

使用 artisan 命令

您可以使用artisan命令从控制台创建角色或权限。

php artisan permission:create-role writer
php artisan permission:create-permission "edit articles"

为特定防护创建权限和角色时,可以将防护名称指定为第二个参数:

php artisan permission:create-role writer web
php artisan permission:create-permission "edit articles" web

单元测试

在您的应用程序的测试中,如果您没有将角色和权限作为测试的一部分进行填充,setUp()那么您可能会遇到鸡/蛋情况,其中角色和权限未在登记处注册(因为您的测试在登记门之后创建它们)完成)。解决这个问题很简单:在测试中只需添加一条setUp()指令来重新注册权限,如下所示:

    public function setUp()
    {
        // first include all the normal setUp operations
        parent::setUp();

        // now re-register all the roles and permissions
        $this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
    }

数据库填充

关于数据库填充的两点说明:

  1. 最好spatie.permission.cache在填充前刷新,以避免缓存冲突错误。这可以通过Artisan命令(请参阅故障排除:缓存部分,稍后)或直接在seeder类中完成(请参阅下面的示例)。

  2. 这是一个示例播种器,它清除缓存,创建权限,然后为角色分配权限:

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        // create permissions
        Permission::create(['name' => 'edit articles']);
        Permission::create(['name' => 'delete articles']);
        Permission::create(['name' => 'publish articles']);
        Permission::create(['name' => 'unpublish articles']);

        // create roles and assign created permissions

        $role = Role::create(['name' => 'writer']);
        $role->givePermissionTo('edit articles');

        $role = Role::create(['name' => 'moderator']);
        $role->givePermissionTo(['publish articles', 'unpublish articles']);

        $role = Role::create(['name' => 'super-admin']);
        $role->givePermissionTo(Permission::all());
    }
}

扩展 Extending

如果您需要扩展现有RolePermission型号,请注意:

  • 您的Role模型需要扩展Spatie\Permission\Models\Role模型
  • 您的Permission模型需要扩展Spatie\Permission\Models\Permission模型

如果您需要更换现有产品RolePermission型号,请记住以下事项:

  • 您的Role模型需要实施Spatie\Permission\Contracts\Role合同
  • 您的Permission模型需要实施Spatie\Permission\Contracts\Permission合同

在两种情况下,无论是扩展还是替换,您都需要在配置中指定新模型。为此,您必须在使用以下命令发布配置后更新配置文件中的models.rolemodels.permission值:

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

高速缓存 Cache

缓存角色和权限数据以加快性能。

使用提供的方法操作角色和权限时,将自动为您重置缓存:

$user->assignRole('writer');
$user->removeRole('writer');
$user->syncRoles(params);
$role->givePermissionTo('edit articles');
$role->revokePermissionTo('edit articles');
$role->syncPermissions(params);
$permission->assignRole('writer');
$permission->removeRole('writer');
$permission->syncRoles(params);

但是,如果您直接在数据库中操作权限/角色数据而不是调用提供的方法,那么除非您手动重置缓存,否则您将看不到应用程序中的变更。

手动缓存重置

要手动重置此程序包的缓存,请运行:

php artisan cache:forget spatie.permission.cache

缓存标识符

提示:如果您正在利用缓存服务,例如redis或者memcached服务器上运行其他站点,则可能会遇到缓存冲突。

设置缓存标识符,缓存前缀名称 prefix 在 /config/cache.php 给不同的应用设置不同的前缀. 防止不同应用之前错误使用或更改缓存的情况

需要用户界面?

此包没有开箱即用的任何UI,你可以自己构建。

测试

composer test
更新于:2018-07-16 13:37:42
返回顶部