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

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

Related

Laravel 6 - Auth::guard('user')->user return null

I create a multiple Authentication in Laravel. When I login with user, on debug in post login method, after Auth::guard('user')->attempLogin..... I see a user but after redirect to HomeController this return null.
How to resolve? I'm beginner in Laravel.
Thank's!!!
/routes/auth/user.php
Route::prefix('backoffice')->name('user.')->namespace('User')->middleware('user')->group(function () {
Auth::routes();
Route::get('home', 'HomeController#index')->name('home');
});
/routes/web.php
Route::group(['middleware' => 'web'], function() {
require 'auth/user.php';
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('cadastro', 'CadastroController');
});
/app/Controllers/User/Auth/LoginController - #post Login
public function login(Request $request) {
$credentials = [
'username' => $_POST['username'],
'password' => $_POST['password']
];
Auth::guard('user')->attempt($credentials, false);
//dd('auth', Auth::guard('user'));
return redirect()->intended('/backoffice/home');
}
/app/Controllers/User/HomeController
public function __construct()
{
$this->middleware('user');
dd('after middleware', Auth::guard('user'), Auth::guard('user')->user());
}
public function index()
{
return view('user.home');
}
By default, Laravel doesn't ship with auth guard user. Perhaps you meant to use web guard i.e Auth::guard('web'). Auth::guard()->user() should return the logged in user object if a user is logged in.
Also, the default middleware for checking logged in user is auth, not user. So, your route might look like this: Route::prefix('backoffice')->name('user.')->namespace('User')->middleware('auth')->group(function () {});, except you've defined a custom middleware in app/Http/Kernel.php $routeMiddleware array with alias user

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

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 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