confrariaweb/laravel-acl

laravel 访问控制包 - ACL

dev-main 2023-06-06 13:41 UTC

This package is not auto-updated.

Last update: 2024-09-26 09:06:33 UTC


README

这是一个简单、易于使用的 Laravel 访问控制 (ACL) 包。

包页面: https://confrariaweb.github.io/laravel-acl

包安装

开始之前,您需要确保已配置数据库访问设置。

在终端中,只需使用以下命令行。

composer require confrariaweb/laravel-acl

安装完成后,请将以下项添加到 app/http/kernel.php 中的 $routeMiddleware 数组。

'check.permission' => \ConfrariaWeb\Acl\Middleware\CheckPermission::class,

如果未使用 "confrariaweb / laravel-user" 包,则应执行以下配置步骤。如果使用此包,则无需执行以下配置,因为它已包含在 "laravel-user" 包中。

class User extends Authenticatable
{
	//add this call to the application's user model
	use \ConfrariaWeb\Acl\Traits\AclTrait;

下一步是将配置文件放置在 "/config" 目录中。

php artisan vendor:publish --provider="ConfrariaWeb\Acl\Providers\AclServiceProvider"

我们即将完成,以下命令将重新构建配置缓存并运行表的迁移。在命令终端中,键入以下命令。

php artisan config:cache
php artisan migrate

可选:您可以使用以下命令在数据库中创建一些条目,这不是强制的,您可以在方便的时候修改它们。

php artisan db:seed

执行上述过程后,包已可用于使用。

包使用

此包可以在应用程序的各个点使用。

在中间件中使用

使用中间件时,它使用路由名称作为权限参数。以下示例检查用户是否具有访问该路由的 'admin.profile' 权限。

Route::get('admin/profile', function () {
    //
})->middleware('check.permission')->name('admin.profile');

在控制器中使用

在控制器上使用访问控制的正确方式如下。

按角色

abort_unless(Auth::user()->hasRole('name-role'), 403);

按权限

abort_unless(Auth::user()->hasPermission('name-permission'), 403);

使用示例

<?php
namespace  App\Http\Controllers;
use Illuminate\Http\Request;
class  HomeController  extends  Controller
{
	public  function  index()
	{
		/*Here we check if the user is included in the roles of editing users*/
		abort_unless(Auth::user()->hasRole('edit-user'), 403);
		return  view('home');
	}
}

在视图中使用

为了在视图 (.blade) 中进行版本控制,您可以使用按角色或权限的控制。

按角色

@role('name-role')
<p>this content is only visible to those who have permission...</p>
@endrole

按权限

@permission('name-permission')
<p>this content is only visible to those who have permission...</p>
@endpermission

许可协议

Laravel 框架是开源软件,根据 MIT 许可协议 许可。