2

有人可以帮我解决中间件吗?我得到了一个无休止的重定向,这让我疯狂了一个星期。

/****** Route **********/
Route::group(['middleware' => 'auth'], function() {
    Route::get('/profile', 'UserController@profile');

    // Superadmin & Admin
    Route::group(['middleware' => 'admin'], function() {
        Route::get('/dashboard', 'UserController@dashboard');
    });

    // Superadmin
    Route::group(['middleware' => 'superadmin'], function() {
            Route::get('/settings', 'UserController@settings');
    });
});

/****** Middleware *******/
// admin
public function handle($request, Closure $next)
{
    if (Auth::check()) {
        if (User::isAdmin()) { // validate if superadmin or admin
        return $next($request);
    } else {
        return redirect('/profile');
    } 
}

// superadmin
public function handle($request, Closure $next)
{
    if (Auth::check()) {
    if (User::isSuperAdmin()) { // validate if superadmin
        return $next($request);
    } else {
        return redirect('/profile');
    }
    }
}

好的,刚刚再次更新了代码,但仍然存在永远重定向任何想法的问题?

// SuperAdmin
public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            if (!User::isSuperAdmin()) {
                return new RedirectResponse(url('/profile'));
            }
        }

        return $next($request);
    }

// admin and superadmin
public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            if (!User::isAdmin()) {
                return new RedirectResponse(url('/profile'));
            }
        } 

        return $next($request);
    }

// auth
public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('/login');
            }
        }
    return $next($request);
}
4

1 回答 1

1

修复。原因是因为 $middleeware 和 $routeMiddleware 都使用相同的中间件

protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\VerifyCsrfToken',
        //'App\Http\Middleware\SuperAdminMiddleware',
        //'App\Http\Middleware\AdminMiddleware',
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth'          => 'App\Http\Middleware\Authenticate',
        'auth.basic'    => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest'         => 'App\Http\Middleware\RedirectIfAuthenticated',
        'admin'         => 'App\Http\Middleware\AdminMiddleware',
        'superadmin'    => 'App\Http\Middleware\SuperAdminMiddleware',
    ];
于 2015-02-26T06:09:02.907 回答