[英]Customizing auth middleware - Laravel 5
The delivered auth
middleware that comes with Laravel 5 is great for user-only routes and controllers, however I want to add the ability to also check if the user is an administrator. Laravel 5随附的已交付
auth
中间件非常适合仅用于用户的路由和控制器,但是我想添加一种功能,还可以检查用户是否是管理员。
Currently, in my controllers, I have this for every class: 当前,在我的控制器中,每个班级都有这个:
if (Auth::user()->level <= 1) {
// admin can do these actions
} else {
// redirect
}
It's very redundant and I'd like to look at what my options are. 这是非常多余的,我想看看我的选择是什么。 Since I want to retain the original
auth
middleware for user authentication, should I be building a new one for administrator authentication, or can I make some simple change in the original auth
middleware that can account for my code above? 由于我想保留用于用户身份验证的原始
auth
中间件,我应该为管理员身份验证构建一个新的中间件,还是可以对可以解释上述代码的原始auth
中间件进行一些简单的更改?
Middleware in Laravel 5.0 do not support arguments (this will be added in the upcoming 5.1 release). Laravel 5.0中的中间件不支持参数(将在即将发布的5.1版本中添加)。
Your options are to either create a separate middleware for this, or use route filters. 您的选择是为此创建单独的中间件,或使用路由过滤器。
You can create a route filter by putting this in your RouteServiceProvider
's boot
method: 您可以通过将其放入
RouteServiceProvider
的boot
方法中来创建路由过滤器:
$router->filter('userLevel', function($route, $request, $level)
{
$user = auth()->user();
if ( ! $user || $user->level > $level)
{
return response('Unauthorized', 401);
}
});
Then use that filter in your routes: 然后在您的路线中使用该过滤器:
Route::group(['before' => 'userLevel:1'], function($router)
{
// define routes...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.