I am using the laravel-permission package. I've created 2 roles, admin
and user
, and associated the admin
role with a permission Access CMS
. I've also created two users, one with the admin
role and one with the user
role.
I've put all my admin
routes behind AdminMiddleware
:
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'isAdmin']], function() {
// Routes
}
The middleware comes from this tutorial :
public function handle($request, Closure $next)
{
if (!Auth::user()->hasPermissionTo('Access CMS')) {
die('aargh');
}
return $next($request);
}
This works with the user with the admin
role. The problem is that when I log in with the other user, it die
s (as it should) but the user remains logged in. Ie if I echo out the Auth::user()
after this attempt it shows the non- admin
user. What I am expecting is that it prevents that user being logged in at all. What am I missing?
Might not be the best option but you could try.
Auth::logout();
Then return the user to home once they have been logged out.
You are missing that the auth
middleware is executed first. Middlewares are executed in the order that they're declared in the array. routing groups
To achieve not logging in at all, you will have to change the order of the middlewares, but you would not be able to use Auth::user()
anymore since the user would not be authed. So to do this without Auth::user()
you would have to query the database yourself to find the user object and then check the permission. This is not recommended though. Why does it matter at all whether the user is authed?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.