Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 - Using Auth::check() not working in MIddleware

I am trying to make a middleware for different type of users in my Laravel 5.2 app. So, what is I am doing is making different middlewares for different users.

As far as I am knowing Auth::check() will not work without musing middleware web from here.

So, what I have done is-

routes.php

Route::group(['middleware' => ['web','admin']], function ()
{
    //suspend, activate, delete
    Route::get('users', [
        'uses'          => 'AdminController@users',
        'as'            => 'users'
    ]);

    //Edit,activate,suspend, delete
    Route::get('articles', [
        'uses'          => 'AdminController@articles',
        'as'            => 'articles'
    ]);
});

AdminMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            return "asd";
            //return Auth::user();
            //return redirect('home');
        }
        else
        {
            return redirect('login');
        }

        //now return the valid request
        return $next($request);
    }
}

Kernel.php

protected $routeMiddleware = [
    'auth'          => \App\Http\Middleware\Authenticate::class,
    'admin'         => \App\Http\Middleware\AdminMiddleware::class,
    'user'          => \App\Http\Middleware\UserMiddleware::class,
    'auth.basic'    => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest'         => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle'      => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

AdminController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function users()
    {
        return view('admin.users');
    }

    public function articles()
    {
        return view('admin.articles');
    }
}

But I am getting this error-

enter image description here

when "return Auth::user();" called inside middleware, "return Auth::user();" is working in other place (view and controllers) but not working like old versions of Laravel.

Can anyone please help?

like image 410
Abrar Jahin Avatar asked Jan 04 '16 04:01

Abrar Jahin


3 Answers

You could potentially do something like this, adjust where needed

public function handle($request, Closure $next)
{
    $user = $request->user();

    if (! $user || $user->user_type != 'admin') {
        return redirect('login');
    }

    return $next($request);
}

The error you are receiving is coming from the fact that you are not returning a Response object from your middleware. The VerifyCsrfToken middleware is trying to add a cookie to the response it gets from passing the request down the pipeline. In this case it is not getting a Response object but instead a string or User because a string or User was returned in your middleware.

like image 170
lagbox Avatar answered Nov 20 '22 03:11

lagbox


Hi @Cowboy and @lagbox , Thanks for trying to help, unfortunately they were not working, but I have solved it.

I have solved it by running-

php artisan cache:clear

composer dump-autoload

php artisan clear-compiled

php artisan optimize

and then middleware-

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            if(strcmp( "admin" , Auth::user()->user_type ) != 0 )
                return redirect('home');
            else
                return $next($request);
        }
        else
        {
            return redirect('login');
        }

        //now return the valid request
        //return $next($request);
    }
}

And Route-

Route::group(['middleware' => ['web','admin']], function ()
{
    //suspend, activate, delete
    Route::get('users', [
        'uses'          => 'AdminController@users',
        'as'            => 'users'
    ]);

    //Edit,activate,suspend, delete
    Route::get('articles', [
        'uses'          => 'AdminController@articles',
        'as'            => 'articles'
    ]);
});
like image 45
Abrar Jahin Avatar answered Nov 20 '22 04:11

Abrar Jahin


You have added routes in web group as well so make sure your kernel file should have following middleware group.

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

The error due to session. make sure your kernel file contains session middlewares.

like image 1
Cowboy Avatar answered Nov 20 '22 03:11

Cowboy