限制非管理员用户的路由访问

Restrict route access to non-admin users

目标

我正在尝试为我的登录用户创建管理员路由限制。 我已经尝试检查我的用户是否是 log-in,以及用户类型是否是 Admin,如果是,我想允许他们访问管理路由,否则,回复404.


routes.php

<!-- Route group -->
$router->group(['middleware' => 'auth'], function() {

    
    <!-- No Restriction -->
    Route::get('dashboard','WelcomeController@index');
   
    <!-- Admin Only -->
    if(Auth::check()){
        if ( Auth::user()->type == "Admin" ){

            //Report
            Route::get('report','ReportController@index');
            Route::get('report/create', array('as'=>'report.create', 'uses'=>'ReportController@create'));
            Route::post('report/store','ReportController@store');
            Route::get('report/{id}', array('before' =>'profile', 'uses'=>'ReportController@show'));
            Route::get('report/{id}/edit', 'ReportController@edit');
            Route::put('report/{id}/update', array('as'=>'report.update', 'uses'=>'ReportController@update'));
            Route::delete('report/{id}/destroy',array('as'=>'report.destroy', 'uses'=>'ReportController@destroy'));

        }
    }

});

结果

它没有按我的预期运行。它抛出 404 错误 - 即使对于管理员用户也是如此。

对于这个简单的案例,您可以使用 Middleware

  1. 创建中间件:
php artisan make:middleware AdminMiddleware
namespace App\Http\Middleware;

use App\Article;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class AdminMiddleware
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->getUser()->type !== "admin") {
            abort(403, 'Unauthorized action.');
        }

        return $next($request);
    }
}
  1. 将其添加到 app\Http\Kernel.php:
protected $routeMiddleware = [
    'admin' => 'App\Http\Middleware\AdminMiddleware',
];
  1. 在路由中使用中间件:
Route::group(['middleware' => ['auth', 'admin']], function() {
    // your routes
});

这个答案是关于为什么你的代码没有按预期工作。 @limonte 的解决方案是正确的,也是我能想到的最好的。

您的路由文件被解析以获取您的路由,之后,这些路由可能会缓存在其他地方。

因此,您不应放置任何依赖于请求的代码(例如,检查用户是否有足够的权限访问路由)。

特别是,您不应在 routes.php 中使用以下依赖于请求的模块(并非详尽无遗):

  • Auth
  • DB 或任何可能依赖于时间的数据库查询
  • Session
  • Request

您应该将 routes.php 视为配置的一部分,它恰好是直接用 php 编写的,而不是您必须学习的某种新语言。