Laravel 5.5 Permissions - User does not have the r

2019-08-05 02:05发布

I'm trying to find a solution in a use case where the admin user does not have the assigned role. In dashboard view it doesn't render the url for users, while if I directly access the dashboard/users, I get:

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

app/Http/Kernel.php

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

routes/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');
   }
);

view/dashboard.blade.php

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

I have successfully generated the default roles & permission with

Commands/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]);
   }

What it could possibly goes wrong? Thanks for you time.

1条回答
Fickle 薄情
2楼-- · 2019-08-05 02:33

You should overwrite the render method to redirect (or whatever you want to do). Go to Expections/Handler.php and overwrite the render function like this:

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

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

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

查看更多
登录 后发表回答