限制对非管理员用户的路由访问 [英] Restrict route access to non-admin users
本文介绍了限制对非管理员用户的路由访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为我的登录用户创建管理员路由限制.
我尝试检查我的用户是否为log-in
,以及用户类型是否为Admin
,如果是,我希望允许他们访问管理路由,否则,响应404. /p>
routes.php
I'm trying to create Admin route restriction for my log-in users.
I've tried a check to see if my user is log-in
, and also if the user type is Admin
, and if they are, I want to allow them access to the admin route, otherwise, respond a 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用户.
Result
It's not working as I intended. It throws 404 error - even for Admin users.
推荐答案
在这种简单情况下,您可以使用中间件.
You can use Middleware for this simple case.
- 创建中间件:
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
});
这篇关于限制对非管理员用户的路由访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文