How to integrate Spatie's laravel-permission with JetStream properly?
Asked Answered
I

2

7

I have a nicely working basic install of Laravel JetStream and Spatie's laravel-permission in Laravel 8.

I can assign a role to the user during registration via

$user->assignRole('visitor');
return $user;

and can restrict the available menu items on the user's dashboard through the permissions I have assigned to the role in my seeder filés run method:

Permission::create(['name' => 'access profile']);
Permission::create(['name' => 'access logout']);

$visitor = Role::create(['name' => 'visitor']);
$visitor->givePermissionTo('access profile');

and through the can directive in the view, like:

@can('access profile')
<!-- Account Management -->
<div class="block px-4 py-2 text-xs text-gray-400">
    {{ __('Manage Account') }}
</div>

<x-jet-dropdown-link href="{{ route('profile.show') }}">
    {{ __('Profile') }}
</x-jet-dropdown-link>
@endcan

So by that, I can hide the menu item as per role but unfortunately, I can still access the functionality directly, by knowing the exact URL.

I guess I have to write a middleware to restrict access to certain functions, but how exactly?

What is the proper and accepted way to handle this problem in this stack?

Thanks! Armand So everything seems fine BUT (!)

How is it possible to forbid direct access to the hidden items? I guess in this case routes are controlled by sanctum, while roles and permissions are by Spatie's package.

Is it possible to link the two?

Thanks!

Interposition answered 17/7, 2021 at 12:52 Comment(0)
S
1

Did you try this? It seems like they added exactly the same for Spatie. Nevertheless I think you need to add a gate permission check like

abort_if(Gate::denies('permission'), Response::HTTP_FORBIDDEN, '403 Forbidden');

on every action

Stopping answered 30/8, 2021 at 13:42 Comment(0)
V
0

I would see if you can utilize laravel's built in can middleware. Then you might be able to update your route definitions. Something like

Route::get('/profile', 'ProfileController@index')->middleware('can:access profile');

I haven't done this with the package you're using, but I think it should work if the other built-in functionality like blade @can work.

Venose answered 12/1, 2022 at 21:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.