Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel backpack restrict user access to admin panel

I'm trying to change checkIfUserIsAdmin() method in CheckIfAdmin middleware for disabling access to all users without role admin

What happened: Nothing. backpack_user()->can(...) or backpack_user()->role(...) don't working... Is that right way to restrict user access to admin panel?

bp - 3.5

laravel - 5.7

php - 7.2

like image 724
user137 Avatar asked Dec 08 '22 12:12

user137


2 Answers

First, create a middleware:

php artisan make:middleware AdminMiddleware

In this file we will check that the user has ‘admin’ role

<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if (! \Auth::user()->hasRole('admin')) 
            return response(trans('backpack::base.unauthorized'),401);
        return $next($request);
    }
}

Now, add this middleware to /config/backpack/base.php

(don’t delete CheckIfAdmin middleware, just append it)

'middleware_class' => [
    \Backpack\Base\app\Http\Middleware\CheckIfAdmin::class,
    \App\Http\Middleware\AdminMiddleware::class
],

Offcourse we must cache the config then

php artisan config:cache
like image 123
merdan Avatar answered Feb 23 '23 19:02

merdan


One way is to make a Middleware in Http\Middleware like CheckIfAdmin.php with below function.

private function checkIfUserIsAdmin($user)
    {
        return ($user->is_admin == 1);
    }

Then add this middleware in array $routeMiddleware of Http\Kernel.php. Like below.

'admin' => \App\Http\Middleware\checkIfUserIsAdmin::class,
like image 29
Rudolph Avatar answered Feb 23 '23 21:02

Rudolph