Laravel Multi Auth using Middle ware - php

I have created an app with user_type(stored in table) as admin,user,super_admin and Created 2 middle wares such as Admin and super Admin.
When i try to login as user and access a function which is set to admin it redirects correctly to home page, when admin tries to access its accessing correctly, but when super admin tries to access the same function which is assigned to admin its not accessing where i have set correct param and routing for super admin same as admin, Please take a look below of my code
This is my admin-middle ware:
public function handle($request, Closure $next, $guard = 'admin')
{
if (Auth::user()->user_type =='admin') {
return $next($request);
} else {
return redirect('home')->with('error','You have not admin access');
}
}
This is my super-admin middle-ware:
public function handle($request, Closure $next, $guard = 'super_admin') {
if (Auth::user()->user_type =='super_admin') {
return $next($request);
} else {
return redirect('home')->with('error','You have not admin access');
}
}
This is my routing web.php
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/contact', 'StudentController#create')->name('contact');
//User Activate
Route::group(['middleware' => ['admin'], 'namespace' => 'Admin', 'prefix' => 'admin'], function(){
Route::resource('/admin', 'AdminController');
Route::get('/get-users/', 'AdminController#getUsers');
Route::get('/get-cfs/', 'AdminController#getCfs');
Route::get('/random-user/', 'AdminController#randomUser');
//Route::resource('/student', 'StudentController');
});
Route::group(['middleware' => ['superadmin'], 'namespace' => 'SuperAdmin', 'prefix' => 'superadmin'], function(){
Route::resource('/superAdmin', 'SuperAdminController');
Route::get('/get-users/', 'AdminController#getUsers');
Route::get('/get-cfs/', 'AdminController#getCfs');
Route::get('/random-user/', 'AdminController#randomUser');
});

You did not specify that super admin has all the privileges that and admin has. You are just specifying two guards super_admin and admin. But how can laravel know that super_admin has all the privileges that an admin has ? You should implement this or you can simple do this in your admin middleware.
public function handle($request, Closure $next, $guard = 'admin')
{
if (Auth::user()->user_type =='super_admin' || Auth::user()->user_type =='admin') {
return $next($request);
} else {
return redirect('home')->with('error','You have not admin access');
}
}

Related

Handling Admin and User Authentication - Laravel

I have 2 two users (Admin and operators) for my system and i want to authenticate them to their various pages based on their roles. I am using the Authenticated.php middleware to achieve this job like below
but i get an error when trying to login with any of the users as
Call to undefined method Illuminate\Contracts\Auth\Factory::check()
What am i doing wrong please?
Authenticated.php
public function handle($request, Closure $next, ...$guards)
{
if(Auth::check()) {
if(Auth::user()->hasRole('administrator')) {
return redirect('/');
} else if (Auth::user()->hasRole('operator')) {
return redirect('client/dashboard');
}
}
// $this->authenticate($guards);
return $next($request);
}
Route.php
Route::group(['middleware' => ['auth']], function () {
Route::get('/', 'PagesController#dashboard');
});
Route::group(array('prefix' => 'client', 'namespace' => 'User', 'middleware' => ['auth']), function () {
Route::get('/dashboard', 'DashboardController#create');
});
Aren't you messing up with your if condition? Try the below code in your RedirectIfAuthenticated.php file in App\Http\Middleware. Hope that will resolve your problem.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if(Auth::user()->hasRole('administrator'))
{
return redirect('/');
}
else
{
return redirect('client/dashboard');
}
}
return $next($request);
}
And Are you using Entrust for handling roles?

Laravel change main page after login

I would like show other main page after login to the user.
Route::get('/', 'PagesController#getIndex');
Route::group(['middleware' => 'auth'], function () {
Route::get('/', 'BlogController#getUserBlog');
});
When user is log in I would like to show BlogController#getUserBlog it's working but, when user is not authenticated laravel shows /login page not PagesController#getIndex. How to correct this for:
Auth user: BlogController#getUserBlog
Guest: PagesController#getIndex
Make changes in this Middleware RedirectIfAuthenticated
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
//Logged In
return redirect()->route('getUserBlog');
}
// Not Logged In
return redirect()->route('getIndex');
}
and make the necessary change in your routes file
Route::get('/', 'PagesController#getIndex')->name('getIndex');
Route::get('/', 'BlogController#getUserBlog')->name('getUserBlog');
Or you can do it without middleware :
Route::group(['prefix' => '/'], function()
{
if ( Auth::check() )
{
Route::get('/', 'BlogController#getUserBlog');
} else{
Route::get('/', 'PagesController#getIndex');
}
});

Laravel auth redirection

I have trouble redirecting after user authentication. I would like to redirect admin to admin panel, and user to home so I made admin middleware:
public function handle($request, Closure $next)
{
if (Auth::user() && Auth::user()->isAdmin()) {
return $next($request);
}
return redirect('/');
}
Routes for admin panel are:
Route::prefix('admin')->middleware(['web', 'admin', 'auth'])->group(function () {
Route::get('/', 'HomeController#index');
Route::resource('user', 'Admin\UserController');
});
I have User and Role models in a M-2-M relationship.
User model:
public function role(){
return $this->belongsToMany('App\Role');
}
public function isAdmin()
{
return ($this->role->first()->name == 'Admin') ? true : false;
}
Auth LoginController:
protected $redirectTo = '/admin';
Auth RedirectIfAuthenticated:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
Issue I'm having is that I always end up on home page. When watching through the inspector I noticed something strange, don't know if it is a standard procedure or not:
Login seems to be triggered twice? Route to /admin was triggered and got 200 OK status, but I never got to see it. If I manually enter it to the browser however, it will lead me to the admin dashboard.

How to group laravel routes based on logged users and guest users

I want to group the Laravel 5 routs based on the logged users and guest users. Is there any inbuilt framework methods in Laravel 5 to do this?
Yes, there are some: https://laravel.com/docs/master/middleware#assigning-middleware-to-routes auth for authorized and guest for guests.
Route::group(['middleware' => ['auth']], function () {
//only authorized users can access these routes
});
Route::group(['middleware' => ['guest']], function () {
//only guests can access these routes
});
Yes, you can do this by updating following method in Authenticate.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
If you are using Sentinel you can check the the logged user from
Sentinel::check() instead of Auth::guard($guard)->guest()
Then you can group the routs as follows.
Route::group(['middleware' => ['auth']], function () {
// Authorized routs
});
Route::group(['middleware' => ['guest']], function () {
// Guest routs
});

Laravel 5.1 Middleware users types redirections

I am trying to make an app in Laravel 5.1.
In my users table I have 3 types of users, admin, agent and farmer. In the users table there is a column named user_type_id where admin is user_type_id=1, agent is user_type_id=2 and farmer is user_type_id=3.
Admin has permission to do everything where agent has few permission.
Problem is while using middleware, my Authenticate.php and AgentAuthenticate.php middleware files are acting as if they are the same, meaning agent is getting all the powers of admin. is there any logical error? here is the code.
agentAuthenticate.php (middleware)
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
if(! $this->auth->user()->user_type != 2) {
return redirect()->guest('auth/login');
}
return $next($request);
}
Authenticate.php
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
if(! $this->auth->user()->user_type != 1) {
return redirect()->guest('auth/login');
}
return $next($request);
}
routes.php
//guest routes
Route::resource('/farmerPoint','farmerPointController',['only' => ['index', 'show']]);
Route::resource('/crop','cropController',['only' => ['index', 'show']]);
//Admin routes
Route::group(['middleware' => 'auth'], function () {
Route::resource('agent','agentController');
Route::resource('farmer','farmerController');
Route::resource('farmer.crop','farmerCropController');
Route::resource('cropType','cropTypeController');
Route::resource('crop','cropController',['except' => ['index','show']]);
Route::resource('farmerPoint','farmerPointController',['except' => ['index','show']]);
Route::get('/AdminPanel',function(){
return view('frontend.AdminPanel');
});
});
//agent routes
Route::group(['middleware' => 'agent'], function () {
Route::resource('farmer','farmerController');
Route::resource('farmer.crop','farmerCropController');
Route::resource('agent','agentController',['only' => ['index','show']]);
Route::get('/AgentPanel',function(){
return view('frontend.AgentPanel');
});
});
In Authenticate.php it should be:
if($this->auth->user()->user_type != 1) {
return redirect()->guest('auth/login');
}
because you want to make redirection for all users with type different than admin
And in agentAuthenticate.php it should be:
if(!in_array($this->auth->user()->user_type, [1,2])) {
return redirect()->guest('auth/login');
}
because you want to make redirection for all users with type different than agent but if user is admin you don't want to make redirection too (you mentioned Admin has permission to do everything)

Categories