6
votes

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?
2
How is it possible to see the login page if the Auth middleware is applied to it?Mehrdad Hedayati
If my answer helped you then it would be great if you mark it as acceped also. Thank you!Margus Pala

2 Answers

7
votes

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");
  }
}
0
votes

Why not instead of dealing with the Auth filter and trying to "validate" only on a certain condition, in your login code, just check what's the type of the user?

This is my high level code of doing it:

        // get roles which are allowed to login to the admin panel
        $roles = $this->userService->adminRoles(); 

        $user = User::whereUsername(Input::get('username'))->whereIn('role_id', $roles)->first();

        if (is_null($user)) {
            // ...
        }

        // create our user data for the authentication
        $userdata = array(
            'username' => Input::get('username'),
            'password' => Input::get('password'),
        );

        // attempt to do the login
        // Auth::attempt($userdata) ....

This way you only do it once when you attempt the login and that's it?