How can I get current user in middleware? Laravel 5.6
When I try to include class
use Illuminate\Support\Facades\Auth;
and then
Auth::user()
I just get null
Middleware
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class DebugbarMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
echo "<pre>"; var_dump(Auth::user()); echo "</pre>"; die();
return $next($request);
}
}
Authorization
$controller = new LoginController();
$request = new Request();
Auth::logout();
$request->setLaravelSession(session()->driver(session()->getDefaultDriver()));
$user = Auth::loginUsingId($id);
if ($user) {
$controller->authenticated($request, $user);
return $this->sendResponse(['messages' => 'User authorization successfully'], 'M User authorization successfully');
}
return $this->sendError('User not found!');
The global middleware stack runs prior to the session being started and authentication details being available.
Define this at the bottom of the 'web' group or in your route middleware.
Related
I'm working on a website where I have designed an authentication system. The client logs in through email and password. If it is correct it should proceed to the dashboard and should not be able to go back to the login page as long as he/she is logged in. However, middleware keeps directing to the login page saying that 'you have to login first'. Both middleware are registered properly in kernel.php
Kernel.php
protected $routeMiddleware = [
'alreadyLoggedIn' => \App\Http\Middleware\AlreadyLoggedIn::class,
'isLoggedIn' => \App\Http\Middleware\AuthCheck::class ];
Web.php
Route::post('/signin', [customAuthController::class,'loginClient']);
Route::get('/client',[customAuthController::class,'dashboard'])->middleware('isLoggedIn');
Route::get('/signin', [customAuthController::class, 'login'])->middleware('alreadyLoggedIn');
Route::get('/sign_up',[customAuthController::class,'registration'])>middleware('alreadyLoggedIn');
AlreadyLoggedIn (1st Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AlreadyLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId')&& (url('signin')==$request->url()|| url('sign_up')==$request->url()))
return $next($request);
return back();
}
}
IsloggedIn (2nd Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class AuthCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId'))
return redirect('signin')->with('fail','You have to login first');
return $next($request);
}
}
customAuthCheck Controller
class customAuthController extends Controller
{
public function dashboard(){
$data = array();
if(Session::has('loginId')){
$data = client::where('id','=',Session::get('loginId'))->first();
}
return view('auth.client', compact('data'));
}
public function logout(){
if(Session::has('loginId')){
Session::pull('loginId');
return redirect('signin');
}
}
}
https://github.com/faaiz99/web-tech-project
In your AuthCheck class (as you named it isLoggedIn in your kernel) first condition is not what you really want to check .
you want to redict user to login if hes not already logged in .
so condition should be something like :
if(!Session()->has('loginId'))
{
return redirect('signin')->with('fail','You have to login first');
}
addition : Its really better if you use laravel auth .
i strongly suggest you to see laravel auth docs
with laravel authentication you can simply use auth facade in your middleware and that would be something like :
if(!auth()->check())
{
return redirect('signin')->with('fail','You have to login first');
}
Hope that helps .
When I'm logged as Admin( I'm setting a column which has utype="ADM" to verify me as admin in a session).And when I try to access the admin dashboard page I get redirected to login page and so on without accessing the dashboard eventually.
This is my AuthAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AuthAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(session('utype') === 'ADM') {
return $next($request);
}else{
session()->flush();
return redirect()->route('login');
}
return $next($request);
}
}
This is my web.php:
Route::middleware(['auth:sanctum', 'verified', 'authadmin'])->group(function() {
Route::get('/admin/dashboard',AdminDashboardComponent::class)->name('admin.dashboard');
I think the issue is mainly focused on the 'authadmin' argument in the route , please provide some tips and help .Thank you
i used from modular structure in laravel that all module in Module folder that routes registerd in ModuleService provider with:
$this->loadRoutesFrom(__DIR__.'/../Routes/web.php');
when i not use from middleware('web') in route then csrf token return null and when i use from this middleware then when user not logined and try to show dashboard page then show error:
Call to a member function setCookie() on null in middleware
Route
Route::get('account/dashboard', [StaffController::class, 'dashboard'])
->middleware(['web','staff'])->name('staff-dashboard');
middleware:staff
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class staff
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(Auth::guard('staff')->check() == false)
{
return view('staffauth::login');
}
return $next($request);
}
}
how to resolve this problem?
I'm trying to make middleware role for my authentication in my project, this is my middleware called sales.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Sales
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()->role == "sales"){
return $next($request);
}
return redirect()->route('login')->with('error',"You don't have an access");
}
}
and this is the route i protect from middleware
Route::get('dashboard','DashboardController#index')->middleware('sales')->name('dashboard');
and when i try to access dashboard to make sure my route is protected by middleware, it shows error like this
Trying to get property of non-object
i appreciate if you answer this !
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Sales
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::User()->role=='sales'){
return $next($request);
}
return redirect()->route('login')->with('error',"You don't have an access");
}
}
When i try to login into my dashboard, my authentication works well without middleware, but when i apply middleware and try to login to the dashboard i get this.
Which this is linked to the my authenticate middleware file
Middleware/Authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(! Auth::User()) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated. You are not a User.'], 401);
}
abort(403, "You're not a User no permission bro");
}
return $next($request);
}
}
My route is followed by:
Route::get('/auth/signup','UserController#getRegister')->name('getRegister');
Route::post('/auth/signup', 'UserController#userRegister')->name('signup');
Route::post('/auth/signin','UserController#userLogin')->name('user.login');
Route::get('/auth/login', 'UserController#getLogin')->name('login');
Route::get('/', 'UserController#getHome')->name('home');
Route::get('/auth/logout', 'UserController#logOut')->name('logout');
Route::group(['middleware' => 'myauth'], function() {
Route::get('/dashboard', 'UserController#getDashboard')->name('dashboard');
});
Thanks in advance im beginning to think there is a bug because im following the laravel 5.5 practices.