Restricting Laravel log viewer access to Administrators using Spatie Permissions

89 Views Asked by At

I'm using Spatie to manage permissions and installed a log-viewer to see logs. The problem is that everyone can see the logs in the address /log-viewer. I want only the administrator to have access to this panel. How can I do that?

1

There are 1 best solutions below

1
Karl Hill On

You can restrict access to the log viewer by creating a new Laravel middleware that checks if the authenticated user has the 'admin' role. If they do, they can proceed to the log viewer. If not, they will be redirected, or an error will be shown.

php artisan make:middleware AdminMiddleware

This command will create a new middleware file in app/Http/Middleware/AdminMiddleware.php. Open this file and modify the handle method.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && Auth::user()->hasRole('admin')) {
            return $next($request);
        }

        // Redirect to home page or show an error
        return redirect('/');
    }
}

Next, you need to register your middleware in app/Http/Kernel.php.

protected $routeMiddleware = [
    // ...
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

Finally, you can apply this middleware to your log viewer routes in /routes/web.php.

Route::group(['middleware' => 'admin'], function () {
    Route::get('/log-viewer', 'LogViewerController@index');
});

In this code, 'middleware' => 'admin' applies the AdminMiddleware to all routes defined in the group. This means that only users with the 'admin' role can access these routes.