Laravel 5.4: custom Middleware not working in route - php

I created the following Middleware to check user session
<?php
namespace App\Http\Middleware;
use Closure;
class Checkusersession
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->session()->has('admin_name')) {
// user value cannot be found in session
return redirect('adminlogin');
}
return $next($request);
}
}
this is my route:
Route::get('webadmin',['middleware' => 'usersession','Admin_controller#index']);
this is my kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'usersession' => \App\Http\Middleware\Checkusersession::class,
];
this is my controller method that creates session:
public function auth_admin(Request $request)
{
$admin_emai = $request->input('admin_email');
$admin_password = $request->input('admin_password');
$checklogin = DB::table('admin_login')
->select('admin_id','admin_email','admin_name')
->where([
'admin_email' => $admin_email,
'admin_password' => $admin_password
])->first();
if (count($checklogin) > 0) {
$request->session()->put('admin_id',$checklogin->admin_id);
$request->session()->put('admin_name',$checklogin->admin_name);
$request->session()->put('admin_email',$checklogin->admin_email);
return redirect()->action('Admin_controller#webadmin');
} else {
return redirect()->action('Admin_controller#admin_login_page')->with('status','Incorrect Email ID or Password');
}
}
I want the Middleware to check if the session (admin_name) exists or not. If not, redirect the user to the login page. but it is not working. if I access the webadmin (dashboard) directly from url, it gives me access even if the session is not set. Please help.

Your route is wrong, you should write it as (in L5.4):
Route::get('webadmin', 'Admin_controller#index')->middleware('usersession');
Or even:
Route::group(['middleware' => 'auth'], function(){
Route::get('webadmin', 'Admin_controller#index');
});
In L5.3 (as you have tagged the question), and in L5.4 I guess you could also write:
Route::get('webadmin',['middleware' => 'usersession', 'uses => 'Admin_controller#index']);
Also, have you tried just to do a dd(request()); or similar in your middleware-handle function to see that it is actually fired?

Related

auth::check() and auth::user() not working Laravel

I have this Laravel app II'm adding middleware for restricting user based on userType:
Middleware/Client.php:
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class Client
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// $user = $request->user();
if (Auth::check() && Auth::user()->userType == 1) {
return $next($request);
}
else {
return redirect('/');
}
}
}
I also added this in kernel.php:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
'usertype' => \App\Http\Middleware\UserType::class,
'client' => \App\Http\Middleware\Client::class,
'staff' => \App\Http\Middleware\Staff::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
but it's not working when I add this client in web.php:
Route::get('/client_profile','Client\ClientController#getclientdetails')->middleware('client');
It's going in else condition if I login. I tried printing $user but its returning null
update:
Route::get('/client_dashboard', function(){
return view('client.dashboard');
})->middleware('client');
authenticate.php:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('admin.login');
}
}
Note: I have 3 userType, 2 user staff and client working on api and admin is using basic Laravel auth
Auth::check() && Auth::user() Will only work if you are authenticated (logged in).
If you are trying to use Auth::check() && Auth::user() in a Middleware while:
not logged in
trying to log in
It will not work because the request hasn't reached the required function to authenticate your log in request.
Only use the client Middleware when your logged in or else it will not work.

Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of

I have Created a new middleware for checking the user token I have create middleware then adeded to kernal.php and but when i tried to access $request in middleware i am getting the error
Here is my is my middleware code
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;
use App\User;
class CheckToken
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->header('Token') == '123')
{
return ['status' =>2, 'msg' => 'Unathorized'];
}
else
{
return $next($request);
}
}
}
Here is my kernal file
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'verifyToken' => \App\Http\Middleware\CheckToken::class,
];
and I am getting this error
Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of Symfony\Component\HttpFoundation\Response, instance of Illuminate\Http\Request given, called in C:\xampp\htdocs\idoltime\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php on line 62
You may use
// return $request;
if($request->header('Token') == '123')
{
$response = [
'status' => 2,
'message' => 'Unauthorized',
];
return response()->json($response, 413);
}
else
{
return $next($request);
}
I face the same problem but not find any answer on the internet. Here is the solution to how I solved this issue.
Step 1: Create a separate route for example
Route::get('header_token', function() {
return response()->json(['status' =>2, 'msg' => 'Unathorized']);
})->name('header_token');
Step 2: Redirect to header_token route
keep in mind you can not return data as response, so return to a route that will return your data
public function handle($request, Closure $next)
{
if($request->header('Token') == '123')
{
return redirect(route('header_token'));
}
else
{
return $next($request);
}
}
if (auth()->user()) {
return $next($request);
}else{
return JsonResponse::respondError("you are not active email");
}
I solved this problem like this
exit(response()->json( json_encode(['message' => 'Text']), 403) );
echo() - var_dump() - print() - print_r() - also works too...

Check auth with role type in middleware laravel5.5

I know this is very common question but in am stuck in this. I am using Laravel 5.5 and developing an ERP. In ERP some URL only access by Super admin so i create a middleware.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Auth::user();
if($user->user_role_id == 1) {
return $next($request);
} else {
return redirect('/');
}
}
}
I have register this middleware in Kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\CheckAdmin::class
];
and usign this middleware in routes
$routes = [
"students" => "StudentsController",
"teachers" => "TeachersController",
"courses" => "CoursesController",
"subjects" => "SubjectsController",
"colleges" => "CollegesController",
"branches" => "BranchesController",
];
Route::group(['middleware' => ['web', 'auth']], function () use ($routes){
Route::match(["get","post"],'/users','UsersController#index')->middleware('admin');
Route::get('/users/status/{id}','UsersController#setStatus')->middleware('admin');
Route::get('/users/delete/{id}','UsersController#delete')->middleware('admin');
Route::match(["get","post"],'/users/add','UsersController#add')->middleware('admin');
Route::match(["get","post"],'/users/edit/{id}','UsersController#edit')->middleware('admin');
Route::match(["get","post"],'/users/view/{id}','UsersController#view')->middleware('admin');
foreach($routes as $route => $class){
Route::match(["get","post"],'/'.$route,$class.'#index');
Route::get('/'.$route.'/status/{id}',$class.'#setStatus');
Route::get('/'.$route.'/delete/{id}',$class.'#delete');
Route::match(["get","post"],'/'.$route.'/add',$class.'#add');
Route::match(["get","post"],'/'.$route.'/edit/{id}',$class.'#edit');
Route::match(["get","post"],'/'.$route.'/view/{id}',$class.'#view');
}
// additions routes
Route::match(["get","post"],'/courses/assign-subjects','CoursesController#assign_subjects');
Route::match(["get"],'/courses/already-assign-subjects/{id}','CoursesController#already_assigned_subjects');
});
This middleware is not called with users/* routes. When i register this $middleware in kernel.php then its works but Auth::user() return null every time. So how can i check logged in user role?
I read somewhere that in L5.5 version, Session not works in constructor then what is the best approach to check user role in middleware.
For checking admin middleware you can use a nested middleware
Route::group(['middleware' => ['web', 'auth']], function () use ($routes){
Route::match(["get","post"],'/users','UsersController#index')->middleware('admin');
Route::group(['middleware' => ['admin'], function () use ($routes){
Route::get('/users/status/{id}','UsersController#setStatus')->middleware('admin');
Route::get('/users/delete/{id}','UsersController#delete')->middleware('admin');
});
Route::match(["get","post"],'/users/add','UsersController#add')->middleware('admin');
Route::match(["get","post"],'/users/edit/{id}','UsersController#edit')->middleware('admin');
Route::match(["get","post"],'/users/view/{id}','UsersController#view')->middleware('admin');
foreach($routes as $route => $class){
Route::match(["get","post"],'/'.$route,$class.'#index');
Route::get('/'.$route.'/status/{id}',$class.'#setStatus');
Route::get('/'.$route.'/delete/{id}',$class.'#delete');
Route::match(["get","post"],'/'.$route.'/add',$class.'#add');
Route::match(["get","post"],'/'.$route.'/edit/{id}',$class.'#edit');
Route::match(["get","post"],'/'.$route.'/view/{id}',$class.'#view');
}
// additions routes
Route::match(["get","post"],'/courses/assign-subjects','CoursesController#assign_subjects');
Route::match(["get"],'/courses/already-assign-subjects/{id}','CoursesController#already_assigned_subjects');
});
When the admin middleware is outside the web and auth it will always return null
Hope this helps

laravel 5.1 admin role in middleware using Entrust

I am trying to filter route using 'auth' and 'auth.admin' middleware which should be like laravel 4.2's Route::filter. But it's not working.
Here is my route
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'auth.admin']], function()
{
// ...
});
Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'auth.admin' => \App\Http\Middleware\RedirectIfAdmin::class,
'role' => Zizaco\Entrust\Middleware\EntrustRole::class,
'permission' => Zizaco\Entrust\Middleware\EntrustPermission::class,
'ability' => Zizaco\Entrust\Middleware\EntrustAbility::class,
];
RedirectIfAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Entrust;
class RedirectIfAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Entrust::hasRole(config('customConfig.roles.admin'))) {
return redirect()->route('dashboard')
->with('error', 'Access Denied');
}
return $next($request);
}
}
As u said that ur dashboard route is for authenticated user,
But ur checking if user is not in admin role send to dashboard, and when he is sent to dashboard he is redirected back, probably due to another middleware kick in, and that send back to login and from login again to dashboard, so just remove ! from ur if condition.

Laravel Middleware not working on some resource route

I am following a tutorial for making a access level restriction:
https://gist.github.com/amochohan/8cb599ee5dc0af5f4246
I was able to make it work somehow but there's something I need to get working which is not in the tutorial.
Provided I have followed the tutorial. I have setup this resource route:
Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
Route::resource('changeschedule', 'ChangeScheduleController', ['only' => ['index'], 'except' => ['create']]);
});
So what I wanted is just to apply the roles middleware to a resource route but with specific route in that resource only let's say I want to be applied in the index only so I have that route above.
When I go to:
http://localhost/hrs/public/changeschedule
It works fine and the middleware roles is working fine. But why is that when I go to:
http://localhost/hrs/public/changeschedule/create
I am getting
NotFoundHttpException in RouteCollection.php line 161:
So I have a no found route error. Why is that? But when I do
Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
Route::resource('changeschedule', 'ChangeScheduleController');
});
Then it works fine but the middleware is applied to all:
index, create, update, edit, delete
I want it to be in index only.
My code:
Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'roles' => \App\Http\Middleware\CheckRole::class,
];
CheckRole.php
<?php namespace App\Http\Middleware;
use Closure;
class CheckRole{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// Get the required roles from the route
$roles = $this->getRequiredRoleForRoute($request->route());
// Check if a role is required for the route, and
// if so, ensure that the user has that role.
if($request->user()->hasRole($roles) || !$roles)
{
return $next($request);
}
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles'] : null;
}
}
You may try this, create a constructor function and add the middleware from there, for example:
public function __construct()
{
$this->middleware('auth');
$this->middleware('roles:administrator', ['only' => ['index']]);
}
Read the documentation.
Update (The third parameter in the middleware::handle method can take the argument):
public function handle($request, Closure $next, $role)
{
// $role will catch the administrator or whatever you pass
}
You may also check these examples/tutorials on my blog (about middleware).

Categories