Handling Admin and User Authentication - Laravel - php

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?

Related

Laravel Multi Auth using Middle ware

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');
}
}

Restricting Access to Manager users - Laravel 5.5

I am a newbie with Laravel. I am doing a tutorial and i have issues on restricting access to manager users. I have been able to assign roles (manager and members) to my users at the moment. But my issue lies in the Manager Middleware.
If the user is a manager, it doesn't return the $next($request); but instead it routes to /home after authentication and if user isn't a manager, it routes to /home as well instead of /tickets.
There is a file called RedirectIfAuthenticated, i changed the route in there but the issue still remained the same.
So what am i missing to restrict access to my managers?
Manager middleware
public function handle($request, Closure $next)
{
if(!Auth::check())
{
return redirect('/login');
}
else{
$user = Auth::user();
if($user->hasRole('Manager'))
{
return $next($request);
}
else{
redirect('/tickets');
}
}
return $next($request);
}
Routes
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' =>'manager'), function () {
Route::get('users', 'UsersController#index');
Route::get('users/{id?}/edit', 'UsersController#edit');
Route::post('users/{id?}/edit','UsersController#update');
Route::get('roles', 'RolesController#index');
Route::get('roles/create', 'RolesController#create');
Route::post('roles/create', 'RolesController#store');
});
Just do the following:
in the else part: instead of redirect('/tickets'); use return redirect('/tickets');
i.e. it will become:
public function handle($request, Closure $next)
{
if(!Auth::check())
{
return redirect('/login');
}
else{
$user = Auth::user();
if($user->hasRole('Manager'))
{
return $next($request);
}
else{
return redirect('/tickets');
}
}
return $next($request);
}
That's it

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)

Laravel 5 redirect loop error

I trying to make a login and admin script, the problem is that I have a redirect loop I dont know why.
I want the login users and can be in the / path not /home.
If change return new RedirectResponse(url('/')); to return new RedirectResponse(url('/anotherpage')); it works but I want to be /
Routes:
Route::get('/', [
'as' => 'home', 'uses' => 'HomeController#index'
]);
// Tutorials Routes
Route::get('/tutorials', 'HomeController#tutorials');
Route::get('/tutorials/{category?}', 'HomeController#tutorialsCategory');
Route::get('/tutorials/{category?}/{lesson?}', 'HomeController#tutorialsLesson');
// Courses and Series Routes
Route::get('/courses-and-series', 'HomeController#coursesandseries');
// Admin Routes
Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function()
{
Route::get('/admin', function()
{
return 'Is admin';
});
});
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Admin middleware:
public function handle($request, Closure $next)
{
if (Auth::user()->type != 'Admin')
{
return abort(404);
}
return $next($request);
}
RedirectIfAuthenticated:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
Home Controller:
class HomeController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('home');
}
public function tutorials()
{
return view('pages.tutorials');
}
public function tutorialsCategory()
{
return view('pages.tutorials');
}
public function tutorialsLesson()
{
return view('pages.single');
}
public function coursesandseries()
{
return view('pages.coursesandseries');
}
public function single()
{
return view('pages.single');
}
}
You are having these redirection loops because all the methods in HomeController are protected by Guest Middleware.
Since you wish to redirect authenticated users to HomeController#index
Remove $this->middleware('guest'); from HomeController
or
Modify the Guest Middleware to ignore index method
$this->middleware('guest', ['only' => ['tutorials','tutorialsCategory']])
List other methods you wish to protect with Guest Middleware excluding Index method

Categories