Search code examples
laravel-backpack

How to Disallow User Access to CRUD Backend


I've got Backpack for Laravel installed and have been using it for some time as an admin back end on a project. I'm also using the spatie/permission module (might come with Backpack, can't remember) to create users for the front end.

Currently, all users are able to access both front end and back end regardless of the group they belong to. I'd like to change that so that only members in an "admin" group are able to access the back end. I've followed the instructions here for separating front end and back end sessions but that's not really what I want as all users are still able to access both sides of the project.

I'm guessing I need to add a guard to the CRUD routes but I'm finding it to be much harder than it should be. Any pointers on how to do this would be greatly appreciated. TIA.


Solution

  • You can create a new middleware and use it in your routes group for admin routes.

    To create a new middleware use the php artisan command like so: (you can name the new middleware what ever you want:

    php artisan make:middleware RequireAdminRole

    Now, inside your new middleware, on the handle function you can have something like this that returns a 403 Forbidden error message:

    public function handle($request, Closure $next)
    {
    
        $user = auth()->user();
    
        if (!$user) return $next($request);
    
        if (!$user->hasRole('Admin'))
        {
            // if your sessions are decoupled from the frontend
            // you can even logout the user like so:
            // auth()->logout();
    
            abort(403, 'Access denied');
        }
    
        return $next($request);
    }
    

    Here we are using the hasRole method, but there are more that you can use. See the spatie/laravel-permissions documentation for more info.

    Now, let's assign this middleware a 'name' so we can use it in our route groups for the admin. Inside the App\Kernel.php file, in the end, inside the $routeMiddleware array add it and give it a new, for example:

    'isadmin' => \App\Http\Middleware\RequireAdminRole::class,

    And finally, you can add this middleware to your admin routes group (which should be in custom.php file if you're using latest backpack 3.4 version) :

    Route::group([
        'prefix'     => 'admin',
        'middleware' => ['web', 'isadmin', config('backpack.base.middleware_key', 'admin')],
        'namespace'  => 'App\Http\Controllers\Admin',
    ], function () {
        // your routes are here
    });
    

    Now all your requests to the admin routes should be protected by the user role check.

    Please let us know how it went for you, and if you encountered any issues.

    Best regards,

    ~Cristian