Check username in Laravel Middleware - laravel

I need to check the user is logged in and check their username in my Middleware of which verifies if they are an admin or not to limit access to a certain page. How do I get their username?
Using Auth::user() gives me an error from another Middleware.
ErrorException in VerifyCsrfToken.php line 136:
Trying to get property of non-object
Route
Route::get('admin', ['middleware' => 'admin', function() {
echo "You're an admin!";
}]);
Middleware
class VerifyAdmin
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::user()->username == "enayet123")
return $next($request);
}
}

You have to return
return $next($request);
even if your conditional fails so the next middleware can have the request. If you move that outside the conditional if, that should fix your problem.
Your code should look like this:
class VerifyAdmin
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::user()->username == "enayet123") {
// Do the thing you want ... (return or redirect to somewhere else)
redirect()->route('homepage');
}
return $next($request);
}
}
You should always return $next($request) which is necessary to pass the code / request from a particular middleware

In order to get the users details such as username/email you need to use $request->user() rather than Auth::user()
You should then check if the user is an admin by creating a method within the User model and calling that in the Middleware
class VerifyAdmin
{
public function handle($request, Closure $next, $guard = null)
{
$user = $request->user();
if ($user && $user->isAdmin()) {
return $next($request);
}
return redirect('/');
}
}

Related

How to fix this, i try to load dashboard route when the auth middleware is true

But when authentication was success, it shown error Route [/db1] not defined. I hace declared db1 route, but this route can access only if user has session. Anyone can tell me what wrong with my code?
this is my route:
Route::group(['middleware' => ['userSession']], function() { Route::get('/db1', [WasteController::class, 'db1'])->name('db1'); });
this is my kernel in middlewareGroup:
'userSession' => [ \App\Http\Middleware\CheckUserSession::class, ],
this is my middleware:
public function handle($request, Closure $next) {
if ($request->session()->get('status') != 'true') {
//status user cannot be found in session
return redirect('/');
}
return $next($request);
}
i have tried but it show error db1 route not defined
Did you try this?
public function handle($request, Closure $next) {
if ($request->session()->get('status') = 'true') {
//status user cannot be found in session
return $next($request);
}
return redirect('/');
}

Laravel: middleware check if user is softdeleted or not

I am using softdelete for users when a user is deleted.
When logging in or authenticating, all users are authenticated. So, I made a middleware named:
isSoftdeletedorNot
public function handle($request, Closure $next)
{
if ($request->user()->deleted_at == null) :
return $next($request);
else:
Auth::logout();
Session::flush();
Session::regenerate();
return redirect()->route('login')->withErrors(['suspended' => 'Your account is deactivated']);
endif;
}
It executes well. The problem is the redirected route shows 404 error and when I manually hard refresh it, it works again.
Try this
public function handle($request, Closure $next)
{
if ($request->user()->deleted_at != null) {
Auth::logout();
Session::flush();
Session::regenerate();
return redirect()->route('login')->withErrors(['suspended' => 'Your account is deactivated']);
}else{
return $next($request);
}
}

Custom Auth Middleware not redirecting properly for unauthorized user

I have created a custom auth controller for recognising unauthorized user and redirect them to login path. If logged in the middlewre is working absolutely fine, but showing error if not logged in. Here is my code
Middleware:
class CheckUserAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
return redirect('login'); // this code is not working
}
}
Error:
try this hope it help
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
return redirect('/login'); OR return redirect(route('login'));
}
class CheckUserAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
// return redirect('login'); // this code is not working
return redirect()->guest('/login');
}
}
redirect()->guest() will redirect if there is no authenticated user.
Example: If an authenticated user is logged in, it won't redirect them as they aren't a guest. If a user isn't logged in, the redirect will happen.
The issue is in circular routing, you are calling from one route, and then return to the same route from the middleware, so your request never reaches the endpoint.
if you call middleware on the...
Route::get('login')->middleware('auth);
...then middleware can not route to 'login' on the fail...
return redirect('login');
... because it will create the loop that never ends. The middleware should reroute to something else, or be placed on other route like 'admin'...
You probably have the middleware on the 'login', that creates the loop, just remove it.

How to get id in Middleware when i use user()

I have a relationship between users and roles. In middleware, I need to get roles to check if the role is 1 or 2. However, I get the following error.
"Trying to get property 'role_id' of non-object."
I am sure I have id 1 in role_id.
User Model
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function handle($request, Closure $next)
{
if (!Auth()->check() && $request->user()->role_id == 1) {
return redirect()->back();
}
return $next($request);
}
Your if statement's logic is mistakenly checking if the user is logged out, while also checking the user's roles. If Auth::check() is false, then the user is not logged in and $request->user() will return null.
Removing the ! from the conditional will fix the error you're receiving.
public function handle($request, Closure $next)
{
if (Auth()->check() && $request->user()->role_id == 1) {
return redirect()->back();
}
return $next($request);
}
However, this will allow all guests to proceed, which you may not want. Assuming you want the middleware to only allow logged-in users with a specific role to proceed, use a more white-listed approach like this:
public function handle($request, Closure $next)
{
// Role ID 2 has permission to proceed
if (Auth()->check() && $request->user()->role_id == 2) {
return $next($request);
}
// Everyone else should go back, including logged-in users and guests.
return redirect()->back();
}
[Can't comment so I'm making a post.]
Aken already answered you but I'd suggest one more thing. Don't use 1 or 2 as ID's but constants:
public function handle($request, Closure $next)
{
if (Auth()->check() && $request->user()->role_id == ADMIN) {
return $next($request);
}
return redirect()->back();
}
You don't even need the comments for this one. Maybe even better:
public function handle($request, Closure $next)
{
if (Auth()->check() && $request->user()->isAdmin()) {
return $next($request);
}
return redirect()->back();
}
but you need to implement it on your own.

StaffMiddleware And AdminMiddleware Laravel 5.3

I have 2 Middlewares.
My StaffMiddleware
public function handle($request, Closure $next)
{
if( $request->user()->role->name != 'staff'){
return redirect()->route('store');
}
return $next($request);
}
My AdminMiddleware
public function handle($request, Closure $next)
{
if( $request->user()->role->name != 'admin'){
return redirect()->route('store');
}
return $next($request);
}
The Problem is my UnitController
public function __construct(UnitInterface $unit){
$this->middleware('staff');
$this->middleware('admin);
$this->unit = $unit;
}
It should work either the role is a staff or an admin. Do I need to create another Middleware to combine them both?
This completely depends on the way your Middleware is designed. As you can see from your code, it simple redirects if the role is not staff or not admin so there would be no way for you to have an OR logic.
However, you could use middleware parameters to avoid this.
$this->middleware('role:admin,staff');
This will use the role middleware and pass admin and staff as parameters.
Then you can use these parameters in your middleware:
public function handle($request, Closure $next, ...$params)
{
if(!in_array($request->user()->role->name, $params)){
return redirect()->route('store');
}
return $next($request);
}
This captures the additional parameters into an array $params in which you can check if the user's role matches one of the parameters.
**try this**
public function __construct(UnitInterface $unit){
$this->middleware(function ($request, $next) {
if($request->user()->role->name == 'staff' || $request->user()->role->name == 'admin')
{
return $next($request);
}
return redirect()->route('store')
});
}
No middleware

Resources