Laravel Auth to check only admin / superuser

I am using Laravel 5 on a Windows dev machine. I want to configure and use Auth middleware throughout my application to support authentication. My use case is standard. There are two (or three) user classes - Administrator and Normal (all users who are not administrators will be regular).

The administrator has the obvious role of backend management and, therefore, has a separate routing group / admin / , which should redirect the illegal user to / admin / login . I set it up like this.

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

When the login form is issued , how can I ask Auth to add a filter

  • or just check among those users where "is_admin" is true ?
  • or ask him to join the User and UserRoles table first to identify only users with the administrator role?
+6
source share
2 answers

I recommend that you define other middleware that determines if the user is admin and not modifies auth. Now add this other middleware to your routes, which only administrators can access.

Add some routing middleware as follows

 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"); } } 
+5
source

Why, instead of dealing with the Auth filter and trying to β€œcheck” only on a specific condition, in your login code, why just check which user type?

This is my high level code:

  // 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) .... 

So you only do this once when you try to log in, and what is it?

0
source

Source: https://habr.com/ru/post/985855/


All Articles