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
Related
I'm trying to implement a middleware in Laravel 5.8 which checks if a value is true for a model Customer. I want the app routes to redirect to a route ('login'), for the api routes I want to give a 401 response. I think I'm overseeing something.
This is my Middleware which works for the app routes, but I can't get the middleware to handle the unauthorized requests ($user['dropshipping'] === false) correctly..
public function handle($request, Closure $next)
{
$user = Auth::user();
if($user instanceof Customer) {
if ($user->guard(['web'])['dropshipping']) {
return $next($request);
} elseif($user->guard(['customer-api'])['dropshipping']) {
return $next($request);
} else {
return redirect(route('login'))->with('error', 'Account not activated, please contact TWM BV.');
}
} else {
return $next($request);
}
}
Guards are associated to Auth not to users.
So you can use Auth::guard('guard-name') or auth()->guard('guard')
public function handle($request, Closure $next)
{
$user = Auth::user();
if($user instanceof Customer) {
if (auth()->guard('web')->user()->dropshipping) {
return $next($request);
} elseif(auth()->guard('customer-api')->user()->dropshipping) {
return $next($request);
} else {
return redirect(route('login'))->with('error', 'Account not activated, please contact TWM BV.');
}
} else {
return $next($request);
}
}
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?
I created a simple system to set permissions for users in the admin panel using AdminMiddleware.
Every user has permissions like groups, posts, pages ....
Routes/web:
Route::group(['middleware' => 'admin'], function()
{
Route::get('/admin' , 'admin\AdminController#index')->name('admin');
//all admin panel routes
}
In the AdminMiddleware
public function handle($request, Closure $next)
{
if(Auth::check()){
if ($request->user()->user_type !== 'man')
{
return redirect('/');
}
$user_permissions = Auth::user()->permissions;
foreach($user_permissions as $value){
$controller = Controllers::get_controller($value->controller_id);
$permissions['name'] = $controller->controller_name;
$all_permissions[] = $permissions;
unset($permissions);
}
foreach ($all_permissions as $value){
$controllers[] = trim($value['name']);
}
$request->user()->controllers = $controllers;
return $next($request);
}
else{
return redirect('/login');
}
}
So I get a list of all user permissions which represent controllers names and in every controller (in this controller i check if the user has permission named 'users' to access the users controller to view their data)
protected $user;
public function __construct(){
$this->middleware(function ($request, $next) {
$this->user= Auth::user();
if(!in_array('users',$this->user->controllers)){
session()->flash('error' , 'No permission');
return redirect('/admin');
}
else{
return $next($request);
}
});
}
I use this for every controller and it works for a small project but when it comes to a large project with modules (nWidart/laravel-modules) it'll be hard. What I want is to check for the permission for the whole module not for every single controller in the module. So if I have a module named blog I want to check if the logged in user has permission to access any controller in that module how could this be done?
I created a middleware for every module and in the middleware i get user permissions and check if he the permission to access this group
public function handle($request, Closure $next)
{
if(Auth::check()){
if ($request->user()->user_type !== 'man')
{
return redirect('/');
}
$user_permissions = Auth::user()->permissions;
$user_group = Auth::user()->group_id;
if($user_group == 1){ //all permissions admin
return $next($request);
}
else{
//get user permissions as an array
if(in_array('groups',$user_permissions)){ //module name is groups
return $next($request);
}
else{
return redirect('/home');
}
}
}
else{
return redirect('/login');
}
}
Routes
Route::group(['middleware' => 'admin'], function()
{
Route::get('/admin' , 'admin\AdminController#index')->name('admin');
});
Route::group(['middleware' => 'users'], function()
{
Route::get('/adminUsers' , '\Modules\Users\Http\Controllers\UsersController#index');
});
Route::group(['middleware' => 'groups'], function()
{
Route::get('/groups' , '\Modules\Groups\Http\Controllers\GroupsController#index');
});
I have a laravel application in this application i have following function for login user
public function login() {
try {
$inputs = Input::except('_token');
$validator = Validator::make($inputs, User::$login);
if ($validator->fails()) {
return Redirect::to('/')->with('message', 'Please Enter Valid Credentials');
} else {
$respones = \UserHelper::processLogin($inputs);
if ($respones) {
return Redirect::to('/dashboard')->with('success_message', 'Welcome to Tressly Admin Dashboard');
} else {
return Redirect::to('/')->with('message', 'Please Enter Valid Information ');
}
}
} catch (Exception $ex) {
return CommonHelper::AdminExceptions($ex);
}
}
Now as user logout and presses the back button , browser show previous page as it is present in cache. Now on this page as user tries to access any protected route application It shows following error
I want to redirect it to '/'( home route)as logged out user tries to acess any protect routes following error comes
Class App\Illuminate\Auth\Middleware\AdminAuthenticate does not exist
I have made a custom Authentication Middle , handle function of the middleware is
public function handle($request, Closure $next, $guard = null) {
if (Auth::check()) {
return $next($request);
}
return redirect('/');
}
I have also registered it in kernal.php in $routeMiddleware like
'authAdmin' => \Illuminate\Auth\Middleware\AdminAuthenticate::class,
and protected my route like
Route::group(['middleware' => 'authAdmin'], function () {
///routes
});
Any ideas ?
use
'authAdmin' => \App\Http\Middleware\AdminAuthenticate::class,
Instead of
'authAdmin' =>\Illuminate\Auth\Middleware\AdminAuthenticate::class,
I hope it it will work
Is there a reason you made a custom middleware class that does exactly the same thing as the already present 'auth' middleware?
RedirectifAuthenticated.php does this;
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
https://laravel.com/docs/5.3/authentication#protecting-routes
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)