承接 directorytree/authorization 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

directorytree/authorization

Composer 安装命令:

composer create-project directorytree/authorization

包简介

Native Laravel Authorization.

README 文档

README

An easy, native role / permission management system for Laravel.

Index

Installation

To get started, install Authorization via the Composer package manager:

composer require directorytree/authorization

The Authorization service provider registers its own database migration directory with the framework, so you should migrate your database after installing the package. The Authorization migrations will create the tables your application needs to store roles and permissions:

php artisan migrate

Now insert the DirectoryTree\Authorization\Traits\Authorizable onto your App\Models\User model:

<?php

namespace App\Models;

use DirectoryTree\Authorization\Traits\Authorizable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Authorizable;

    // ...
}

You can now perform user authorization.

Migration Customization

If you would not like to use Authorization's default migrations, you should call the Authorization::ignoreMigrations method in the register method of your AppServiceProvider. You may export the default migrations using php artisan vendor:publish --tag=authorization-migrations.

use DirectoryTree\Authorization\Authorization;

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    Authorization::ignoreMigrations();
}

Model Customization

By default, the App\Models\User class is registered as the authorizable user model.

You're free to extend the models used internally by Authorization, or create your own.

Instruct Authorization to use your own models via the Authorization class in your AuthServiceProvider:

use DirectoryTree\Authorization\Authorization;

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Authorization::useUserModel(\App\Models\User::class);
    Authorization::useRoleModel(\App\Models\Role::class);
    Authorization::usePermissionModel(\App\Models\Permission::class);
}

Be sure to add the relevant traits for each of your custom models:

Role Model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DirectoryTree\Authorization\Traits\ManagesPermissions;

class Role extends Model
{
    use ManagesPermissions;
}

Permission Model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DirectoryTree\Authorization\Traits\HasUsers;
use DirectoryTree\Authorization\Traits\HasRoles;
use DirectoryTree\Authorization\Traits\ClearsCachedPermissions;

class Permission extends Model
{
    use HasUsers, HasRoles, ClearsCachedPermissions;
}

Usage

Authorization uses native Laravel relationships, so there's no need to learn a new API if you don't want to.

Due to Authorization's trait based implementation, all of Authorization's functionality can be overridden or extended with you own implementation.

Managing Roles & Permissions

Create a permission:

use DirectoryTree\Authorization\Permission;

$createUsers = Permission::create([
    'name' => 'users.create',
    'label' => 'Create Users',
]);

Create a role:

use DirectoryTree\Authorization\Role;

$admin = Role::create([
    'name' => 'administrator',
    'label' => 'Admin',
]);

Grant the permission to a role:

$admin->permissions()->save($createUsers);

Now assign the role to the user:

$user->roles()->save($admin);

You may also use the grant() or revoke() method on a Role model:

// Using the permission's name:
$admin->grant('users.create');

// Using a permission model:
$admin->grant($permission);

// Granting multiple permissions:
$admin->grant(['users.create', 'users.edit']);

// Granting a collection of models:
$admin->grant(Permission::all());

// Using a mix of models and permission name:
$admin->grant([$createUsers, 'users.edit']);

You may also sync a role's permissions using the grantOnly() method:

// All permissions will be removed except, except for the given:
$admin->grantOnly('users.create');
// Using the permission's name:
$admin->revoke('users.create');

// Using a permission model:
$admin->revoke($permission);

// Revoking multiple permissions:
$admin->revoke(['users.create', 'users.edit']);

// Revoking a collection of models:
$admin->revoke(Permission::all());

// Using a mix of models and permission name:
$admin->revoke([$createUsers, 'users.edit']);

You may also detach all permissions from a role using revokeAll():

$admin->revokeAll();

Managing Users & Permissions

You can also create user specific permissions:

$createUsers = Permission::create([
    'name' => 'users.create',
    'label' => 'Create Users',
]);

$user->permissions()->save($createUsers);

As with roles, may also use the grant() or revoke() method on an authorizable User model:

// Using the permission's name:
$user->grant('users.create');

// Using a permission model:
$user->grant($permission);

// Granting multiple permissions:
$user->grant(['users.create', 'users.edit']);

// Granting a collection of models:
$user->grant(Permission::all());

// Using a mix of models and permission name:
$user->grant([$createUsers, 'users.edit']);

You may also sync a users' permissions using the grantOnly() method:

// All permissions will be removed except, except for the given:
$user->grantOnly('users.create');
// Using the permission's name:
$user->revoke('users.create');

// Using a permission model:
$user->revoke($permission);

// Granting multiple permissions:
$user->revoke(['users.create', 'users.edit']);

// Granting a collection of models:
$user->revoke(Permission::all());

// Using a mix of models and permission name:
$user->revoke([$createUsers, 'users.edit']);

Checking Permissions & Roles

Using Laravel's native can() method:

if (Auth::user()->can('users.create')) {
    // This user can create other users.
}

Using Laravel's native authorize() method in your controllers:

public function create()
{
    $this->authorize('users.create');

    User::create(['...']);
}

Using Laravel's native Gate facade:

if (Gate::allows('users.create')) {
    //
}

Using Laravel's native @can directive in your views:

@can('users.create')
    <!-- This user can create other users. -->
@endcan

Checking Permissions & Roles (Using Authorization Package Methods)

Checking for permission:

// Using the permissions name.
if ($user->hasPermission('users.create')) {
    //
}

// Using the permissions model.
if ($user->hasPermission($createUsers)) {
    //
}

Checking for multiple permissions:

if ($user->hasPermissions(['users.create', 'users.edit'])) {
    // This user has both creation and edit rights.
} else {
    // The user doesn't have one of the specified permissions.
}

Checking if the user has any permissions:

if ($user->hasAnyPermissions(['users.create', 'users.edit', 'users.destroy'])) {
    // This user either has create, edit or destroy permissions.
} else {
    // The user doesn't have any of the specified permissions.
}

Checking if the user has a role:

if ($user->hasRole('administrator')) {
    // This user is an administrator.
} else {
    // The user isn't an administrator.
}

Checking if the user has specified roles:

if ($user->hasRoles(['administrator', 'member'])) {
    // This user is an administrator and a member.
} else {
    // The user isn't an administrator or member.
}

Checking if the user has any specified roles:

if ($user->hasAnyRoles(['administrator', 'member', 'guest'])) {
    // This user is either an administrator, member or guest.
} else {
    // The user doesn't have any of these roles.
}

Caching

By default all permissions are cached to prevent them from being retrieved on every request.

This cache is automatically flushed when permissions are created, updated, or deleted.

If you would like to disable the cache, call Authorization::disablePermissionCache in your AuthServiceProvider:

use DirectoryTree\Authorization\Authorization;

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Authorization::disablePermissionCache();
}

Cache Key

By default, the permission cache key is authorization.permissions.

To alter the cache key, call Authorization::cacheKey in your AuthServiceProvider:

use DirectoryTree\Authorization\Authorization;

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Authorization::cacheKey('my-key');
}

Cache Expiry

By default, the permission cache will expire daily.

To alter this expiry date, call Authorization::cacheExpiresIn in your AuthServiceProvider:

use DirectoryTree\Authorization\Authorization;

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Authorization::cacheExpiresIn(now()->addWeek());
}

Gate Registration

By default all permissions you create are registered in Laravel's Gate.

If you would like to disable this, call Authorization::disableGateRegistration in your AuthServiceProvider:

use DirectoryTree\Authorization\Authorization;

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Authorization::disableGateRegistration();
}

Middleware

Authorization includes two useful middleware classes you can utilize for your routes.

Insert them into your app/Http/Kernel.php:

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

    // The role middleware:
    'role' => \DirectoryTree\Authorization\Middleware\RoleMiddleware::class,

    // The permission middleware:
    'permission' => \DirectoryTree\Authorization\Middleware\PermissionMiddleware::class,
];

Once you've added them, you can start using them.

Note: When a user does not meet the requirements using the middleware, a 403 HTTP exception is thrown.

To guard a route to only allow specific permissions:

Route::get('users', [
    'uses' => 'UsersController@index',
    'middleware' => 'permission:users.index',
]);

// Multiple permissions:
Route::get('users', [
    'uses' => 'UsersController@index',
    // Users must have index **and** create rights to access this route.
    'middleware' => 'permission:users.index,users.create',
]);

To guard a route to allow a specific role:

Route::get('users', [
    'uses' => 'UsersController@index',
    'middleware' => 'role:administrator',
]);

// Multiple roles:
Route::get('users', [
    'uses' => 'UsersController@index',
    // Users must be an administrator **and** a member to access this route.
    'middleware' => 'role:administrator,member',
]);

Running Tests

To run your applications tests, you must instantiate the PermissionRegistrar inside your TestCase::setUp() method before running your tests for permissions to register properly:

use DirectoryTree\Authorization\PermissionRegistrar;
protected function setUp() : void
{
    parent::setUp();

    app(PermissionRegistrar::class)->register();
}

directorytree/authorization 适用场景与选型建议

directorytree/authorization 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.31k 次下载、GitHub Stars 达 178, 最近一次更新时间为 2021 年 08 月 31 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「authorization」 「acl」 「laravel」 「roles」 「permissions」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 directorytree/authorization 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 directorytree/authorization 我们能提供哪些服务?
定制开发 / 二次开发

基于 directorytree/authorization 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 10.31k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 178
  • 点击次数: 6
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 178
  • Watchers: 1
  • Forks: 9
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-08-31