laravel配置spatie/laravel-permission权限

  • 我是laravel6直接用老版本
composer require "spatie/laravel-permission:5.3"
  • 发布配置文件
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

会在config目录下生成一个文件permission.php

  • 注册配置文件

config/app.php

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

创建表,我是重写权限,之前权限只验证前端,后端没验证,就有人写了外挂~

新版权限SQL:

CREATE TABLE `roles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `guard_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `roles_name_guard_name_unique` (`name`,`guard_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

CREATE TABLE `model_has_permissions` (
  `permission_id` bigint(20) unsigned NOT NULL,
  `model_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `model_id` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`permission_id`,`model_id`,`model_type`) USING BTREE,
  KEY `model_has_permissions_model_id_model_type_index` (`model_id`,`model_type`) USING BTREE,
  CONSTRAINT `model_has_permissions_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions_v2` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

CREATE TABLE `model_has_roles` (
  `role_id` bigint(20) unsigned NOT NULL,
  `model_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `model_id` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`role_id`,`model_id`,`model_type`) USING BTREE,
  KEY `model_has_roles_model_id_model_type_index` (`model_id`,`model_type`) USING BTREE,
  CONSTRAINT `model_has_roles_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

CREATE TABLE `role_has_permissions` (
  `permission_id` bigint(20) unsigned NOT NULL,
  `role_id` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`permission_id`,`role_id`) USING BTREE,
  KEY `role_has_permissions_role_id_foreign` (`role_id`) USING BTREE,
  CONSTRAINT `role_has_permissions_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions_v2` (`id`) ON DELETE CASCADE,
  CONSTRAINT `role_has_permissions_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

CREATE TABLE `permissions_v2` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `display_name` varchar(255) CHARACTER SET utf8mb4 NOT NULL COMMENT '权限名',
  `description` varchar(255) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '权限描述',
  `guard_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `permissions_name_guard_name_unique` (`name`,`guard_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;


INSERT INTO `permissions_v2` (`id`, `name`, `display_name`, `description`, `guard_name`, `created_at`, `updated_at`)
SELECT `id`, `name`, `display_name`, `description`, 'web', `created_at`, `last_updated_at`
FROM `permissions`;

  • 数据表说明:
    roles为角色表
    model_has_permissions为用户所属权限表
    model_has_roles为用户所属角色表
    role_has_permissions为权限所属角色
    permissions_v2为权限表,我这里给重命名了,原先权限有这个表,重命名后可在config/permission.php指定新表明

  • 填充数据

    <?php
    namespace App\Http\Controllers\Api;
    use Illuminate\Http\Request;
    use Illuminate\Validation\ValidationException, Exception;
    use Spatie\Permission\Models\Permission;
    use Spatie\Permission\Models\Role;
    use App\Http\Error\ValidateErr;
    use App\Http\Error\HttpErr;
    use Illuminate\Support\Facades\DB;
    use App\Services\PermissionService;
    class PermissionController extends Controller
    {
      use BaseController;
    
      /**
       * 新增角色
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function addRole(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'name' => 'required|min:1|max:10',
              ]);
              $role = Role::create(['name' => $request->name]);
              if (!$role) {
                  throw new Exception("新增角色错误!");
              }
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 编辑角色
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function editRole(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'id'   => 'required|integer',
                  'name' => 'required|min:1|max:10',
              ]);
              $roleModel       = Role::findById($request->id);
              $roleModel->name = $request->name;
              if (!$roleModel->save()) {
                  throw new Exception("修改失败!");
              }
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 删除角色
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      public function delRole(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'id' => 'required|array',
              ]);
              $intCount = Role::query()->whereIn('id', $request->id)->delete();
              return $this->success([
                  'delete_count' => $intCount
              ]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 角色列表
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function roleList(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $arrInfoList = Role::query()->select(['id', 'name'])->get()->toArray();
              return $this->success($arrInfoList);
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 新增权限
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function addPermission(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'name'         => 'required|min:1|max:10',
                  'display_name' => 'min:1|max:20',
                  'description'  => 'min:1|max:50',
              ]);
              $result = Permission::create($request->all());
              if (!$result) {
                  throw new Exception("新增权限错误!");
              }
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 编辑权限
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function editPermission(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'id'           => 'required|integer',
                  'name'         => 'required|min:1|max:10',
                  'display_name' => 'min:1|max:20',
                  'description'  => 'min:1|max:50',
              ]);
              $permissionModel = Permission::findById($request->id);
              $permissionModel->fill($request->all());
              if (!$permissionModel->save()) {
                  throw new Exception("修改失败!");
              }
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 删除权限
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      public function delPermission(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'id' => 'required|array',
              ]);
              $intCount = Permission::query()->whereIn('id', $request->id)->delete();
              return $this->success([
                  'delete_count' => $intCount
              ]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 权限列表
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function permissionList(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $arrInfoList = Permission::query()->select(['id', 'name'])->get()->toArray();
              return $this->success($arrInfoList);
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 角色添加权限
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function roleAddPermission(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'role_id'       => 'required|integer',
                  'permission_id' => 'required|array',
              ]);
              $roleModel = Role::findById($request->role_id);
              foreach ($request->permission_id as $permission_id) {
                  $permissionModel = Permission::query()->where(['id' => $permission_id])->exists();
                  if (!$permissionModel) {
                      throw new Exception("权限id:{$permission_id}不存在!");
                  }
              }
              if (!$roleModel->givePermissionTo($request->permission_id)) {
                  throw new Exception("角色添加权限失败!");
              }
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 角色删除权限
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function roleDelPermission(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'role_id'       => 'required|integer',
                  'permission_id' => 'required|array',
              ]);
              $roleModel = Role::findById($request->role_id);
              $roleModel->revokePermissionTo(Permission::query()->whereIn('id', $request->permission_id)->get());
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 角色的权限列表
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      public function rolePermissionList(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'role_id' => 'required|array',
              ]);
              $arrInfoList = DB::table(config('permission.table_names.role_has_permissions') . ' AS a')
                  ->leftJoin(config('permission.table_names.permissions') . ' AS b', 'a.role_id', '=', 'b.id')
                  ->select(['a.role_id', 'b.id as permissions_id', 'b.name as permissions_name'])
                  ->whereIn('role_id', $request->role_id)
                  ->get();
              return $this->success($arrInfoList);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 用户分配角色
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function assignRole(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $userModel = PermissionService::checkUserAndRoleIsExists($request);
              if (!$userModel->assignRole($request->role_id)) {
                  throw new Exception("用户分配角色失败!");
              }
              return $this->success([]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 用户角色删除
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function delUserRole(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              PermissionService::checkUserAndRoleIsExists($request);
              $intCount = DB::table(config('permission.table_names.model_has_roles'))->whereIn('role_id', $request->role_id)->where('model_id', $request->user_id)->delete();
              return $this->success([
                  'delete_count' => $intCount
              ]);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    
      /**
       * 用户角色列表
       * @param Request $request
       * @return \Illuminate\Http\JsonResponse
       */
      function userRoleList(Request $request): \Illuminate\Http\JsonResponse
      {
          try {
              $this->validate($request, [
                  'user_id' => 'required|int',
              ]);
              $arrInfoList = DB::table(config('permission.table_names.model_has_roles') . ' AS a')
                  ->leftJoin(config('permission.table_names.roles') . ' AS b', 'a.role_id', '=', 'b.id')
                  ->select(['a.role_id', 'b.id as roles_id', 'b.name as roles_name'])
                  ->where('model_id', '=', $request->user_id)
                  ->get();
              return $this->success($arrInfoList);
          } catch (ValidationException $e) {
              return $this->error(ValidateErr::VALIDATE, '', $e->errors());
          } catch (Exception $e) {
              return $this->error(HttpErr::PERMISSION_ERR, $e->getMessage());
          }
      }
    }
    
    
  • 软件包附带 RoleMiddleware 和 PermissionMiddleware 中间件,将它们添加到你的 app/Http/Kernel.php 文件中,但没用这种方式,我使用自定义名称验证
    先创建中间件

    <?php
    namespace App\Http\Middleware;
    use App\Entities\Users;
    use Spatie\Permission\Exceptions\UnauthorizedException;
    use Closure;
    use Spatie\Permission\Middlewares\PermissionMiddleware as Middleware;
    class Permission extends Middleware
    {
      public function handle($request, Closure $next, $permission, $guard = null)
      {
          $authGuard = app('auth')->guard($guard);
          if ($authGuard->guest()) {
              throw UnauthorizedException::notLoggedIn();
          }
          $user        = Users::find($authGuard->user()->id);
          $permissions = is_array($permission)
              ? $permission
              : explode('|', $permission);
    
          try {
    //            $a = $user->getDirectPermissions();     // 直接权限
    //            $b = $user->getPermissionsViaRoles();   // 从用户角色继承的权限
    //            $c = $user->getAllPermissions();   // 适用于用户的所有权限(继承和直接)
    //            foreach ($permissions as $permission) {
    //                if ($user->hasPermissionTo($permission)) {
    //                    return $next($request);
    //                }
    //            }
              $arrPermissionList = $user->getPermissionsViaRoles()->pluck('name')->toArray();
              foreach ($permissions as $permission) {
                  if (in_array($permission, $arrPermissionList)) {
                      return $next($request);
                  }
              }
              throw UnauthorizedException::forPermissions($permissions);
          } catch (\Exception $e) {
              throw UnauthorizedException::forPermissions($permissions);
          }
      }
    }
  • 注册中间件,将它们添加到你的 app/Http/Kernel.php

    protected $routeMiddleware = [
      // ...
      //权限验证
      'permission_v2' => \App\Http\Middleware\Permission::class,
    ];
  • 使用
      //test
      Route::post('xxx', 'xxxController@xxx')->middleware('permission_v2:订单列表|订单导出');
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!