簡體   English   中英

限制對非管理員用戶的路由訪問

[英]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錯誤-甚至對於Admin用戶。

您可以在這種簡單情況下使用中間件

  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的解決方案是正確的,也是我能想到的最好的解決方案。

解析路由文件以獲取路由,然后,這些路由可能會緩存在其他位置。

因此,您不應放置任何依賴於請求的代碼(例如,檢查用戶是否具有訪問路徑的足夠權限)。

特別是,您不應在route.php中使用以下依賴於請求的模塊(並非詳盡無遺):

  • Auth
  • DB或可能取決於時間的任何類型的數據庫查詢
  • Session
  • Request

您應該將routes.php作為配置的一部分進行查看,只是它是直接用php編寫的,而不是您必須學習的一些新語言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM