Laravel 5.5权限 - 用户没有合适的岗位(Laravel 5.5 Permissions

2019-09-27 15:47发布

我试图找到一个用例的一个解决方案,管理员用户没有指定的角色。 在仪表板视图不会使用户的URL,而如果我直接访问仪表板/用户,我得到:

Spatie \ Permission \ Exceptions \ UnauthorizedException user does not have the right roles

应用程序/ HTTP / Kernel.php

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

路线/ web.php

Route::group(
   ['middleware' => ['role:admin']],
    function () {
      Route::get('/dashboard/users', 'UsersController@index');
      Route::get('/dashboard/users/{id}', 'UsersController@edit');
      Route::patch('/dashboard/users/{id}', 'UsersController@update');
   }
);

视图/ dashboard.blade.php

<div class="panel-body">
  @hasrole('admin')
     <li><a href="/dashboard/users">Manage Users</a></li>
  @endhasrole
</div>

我已经成功地生成的默认角色和权限与

命令/ GenerateRoles.php

    public function handle()
    {
    $this->info('Generating default roles and permissions...');
    $admin = User::create(
      [
        'name'     => 'administrator',
        'email'    => 'adm@mail.com',
        'password' => bcrypt('12345'),
      ]
    );

    // Create roles.
    $adminRole   = Role::create(['name' => 'admin']);
    $supportRole = Role::create(['name' => 'support']);

    $admin->assignRole('admin');

    // Create permissions.
    $userManagement = Permission::create(['name' => 'users management']);
    $deleteImages  = Permission::create(['name' => 'delete images']);
    $datasetStatus   = Permission::create(
      ['name' => 'change dataset building status']
    );

    $adminRole->givePermissionTo($userManagement);
    $deleteImages->syncRoles([$adminRole, $supportRole]);
    $datasetStatus->syncRoles([$adminRole, $supportRole]);
   }

什么它可能出错? 感谢您的时间。

Answer 1:

您应该覆盖的渲染方法来重定向(或任何你想做的事)。 转到Expections / Handler.php并覆盖渲染功能是这样的:

public function render($request, Exception $exception)
{
    if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
          return redirect('/');
    }

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

来源: https://github.com/spatie/laravel-permission#catching-role-and-permission-failures



文章来源: Laravel 5.5 Permissions - User does not have the right roles