0
votes

I want to make a middleware to protect admin routes in laravel 5.2 app. user_type isn't a field in users table in my db, but in a separate table : enter image description here

Admin's user_type_id is 4 I made this middleware :

class AdminMiddleware
{

    public function handle($request, Closure $next)
    {
        $authedUserID = Auth::id();

        $user = User::query()
                ->leftjoin('users_user_types as uut', 'uut.user_id', '=', 'users.id')
                ->where('uut.user_id',"=","$authedUserID")
                ->get(['users.*',
                        'uut.user_type_id as userType'])->first();

        if ($user['userType'] !=4)
        {

            return redirect('/home');
        }

        return $next($request);
    }
}

and put this in $routeMiddleware array in kernel.php :

'admin' => \App\Http\Middleware\AdminMiddleware::class

and this is one of admin routes I want to apply my middleware on :

Route::get('ptyadmin', 'AdminController@show')->middleware('admin');

The Problem is that when I go to this route with admin user(user_type = 4) or normal user(user_type = 1) it redirects to /home in both cases !!

Why does this happen and how can I fix it ??

2
Where is your auth middlewar in route?Mahbub
I put it inside AdminController : public function __construct(User $user, JWTAuth $jwtauth) { $this->middleware('jwt.auth', ['except' => [ ]]); } @mrabbaniRowayda Khayri
Dump dd(Auth::id()) in AdminMiddleware and check the value?Mahbub
Thanks @mrabbani it works when I put jwt.auth middleware in routes.phpRowayda Khayri

2 Answers

1
votes

first method returns object

if ($user->userType !=4)

Also use selectinstead get

->select(['users.*','uut.user_type_id as userType'])->first();
0
votes

It works when I put jwt.auth middleware in routes.php :

Route::get('ptyadmin', 'AdminController@show')
->middleware('jwt.auth')
->middleware('admin');

instead of putting it in AdminController :

public function __construct(User $user, JWTAuth $jwtauth)

{

   $this->middleware('jwt.auth', ['except' => []]);

}