Reputation: 836
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
Upvotes: 6
Views: 6564
Reputation: 5438
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?
Upvotes: 0
Reputation: 8663
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");
}
}
Upvotes: 7