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.
Related
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...
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
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?
I know this may seem duplicated. I have already checked these threads:
https://laracasts.com/discuss/channels/laravel/authuser-returns-null-in-laravel-52
https://medium.com/#mshanak/laravel-5-token-based-authentication-ae258c12cfea#.8qeglhfnq
Auth::user() returns null in Laravel 5.2
Laravel : Auth::user() returns null
But I haven't found the solution to my problem
After successfully getting the access_token for a user using the credentials Auth::user() returns null within the controllers.
Here is my Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class,
'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class,
'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class,
'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class,
'csrf' => \App\Http\Middleware\VerifyCsrfToken::class,
];
Here is my routes.php
Route::group(['prefix' => $api_prefix, 'middleware' => 'oauth', 'namespace' => 'Api'], function () {
Route::resource('user', 'UserController', ['except' => ['create', 'store']]);
Route::resource('post', 'PostController');
Route::post('follow/{user}', 'UserRelationsController#follow');
Route::post('unfollow/{user}', 'UserRelationsController#unfollow');
Route::post('trade/{user}', 'UserRelationsController#trade');
Route::post('untrade/{user}', 'UserRelationsController#untrade');
Route::post('capturetime', 'TimeCaptureController#store');
});
Any help would be appreciated
You need to use Authorizer::getResourceOwnerId() to get the user id. After that you should be able to use Auth::loginUsingId($userId) to log in the user for that request. You could set up a middleware to do this for you, would be something like this:
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$userId = Authorizer::getResourceOwnerId();
if($userId) {
Auth::loginUsingId($userId);
}
return $next($request);
}
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.