Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Auth to validate only admin/superuser

I'm using Laravel 5 on a Windows dev machine. I want to customize and use the Auth middleware throughout my application, to maintain authentication. My use case is a standard one. There are two (or three) classes of users - Admin and Regular (regular would be all users that are not admin).

The Admin has the obvious role of backend management, and hence has a separate routing group /admin/, which should redirect an unlogged user to /admin/login. I have set it up like so..

Route::group(['middleware'=>'auth', 'prefix' => 'admin'], function() {
  Route::get('login','App\AuthController@getLogin');
  Route::post('login','App\AuthController@postLogin');
});

When the login form is posted, how do I ask Auth to add a filter

  • either that only validate from among those users where 'is_admin' is true?
  • or ask it to first join a User and a UserRoles table to identify only users with an Admin role?
like image 557
rolfk Avatar asked Apr 24 '15 08:04

rolfk


1 Answers

I recommend you to define another middleware that detects if user is admin instead of modifying the auth. Now add this another middleware to your routes that only admins can access.

Add several middleware to route like this

Route::group(['middleware' => ['auth','admin']], function() {

Middleware will look something like

public function handle($request, Closure $next) {
  if (Auth::user()->role == "admin") {
    return $next($request);
  } else {
    return redirect("/")->withMyerror("You are not authorized for this action");
  }
}
like image 165
Margus Pala Avatar answered Oct 16 '22 03:10

Margus Pala