[英]Restrict route access to non-admin users
我正在尝试为我的登录用户创建管理员路由限制。 我尝试检查一下我的用户是否log-in
,以及用户类型是否为Admin
,如果是,我希望允许他们访问管理路由,否则,响应404。
<!-- 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用户。
您可以在这种简单情况下使用中间件 。
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);
}
}
app\\Http\\Kernel.php
: protected $routeMiddleware = [
'admin' => 'App\Http\Middleware\AdminMiddleware',
];
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.