如何为路由 laravel 5 使用“OR”中间件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39344836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:25:12  来源:igfitidea点击:

How to use 'OR' middleware for route laravel 5

phplaravellaravel-5laravel-5.2

提问by Govind Samrow

I've two types for user and I've created multiple middlewares.

我有两种类型的用户,我已经创建了多个中间件。

Some routes need to allow for both type of user.

一些路由需要允许两种类型的用户。

I've trying following code:

我正在尝试以下代码:

Route::group(['namespace' => 'Common', 'middleware' => ['Auth1', 'Auth2']], function() {
    Route::get('viewdetail', array('as' => 'viewdetail', 'uses' => 'DashboardController@viewdetail'));
}); 

But its not working :(

但它不起作用:(

回答by jedrzej.kurylo

Middleware is supposed to either return a response or pass the request down the pipeline. Middlewares are independent of each other and shouldn't be aware of other middlewares run.

中间件应该返回响应或将请求传递到管道中。中间件彼此独立,不应该知道其他中间件在运行。

You'll need to implement a separate middleware that allows 2 roles or single middleware that takes allowed roles as parameters.

您需要实现一个单独的中间件,该中间件允许 2 个角色或将允许的角色作为参数的单个中间件。

Option 1: just create a middleware is a combined version of Auth1 and Auth2 that checks for 2 user types. This is the simplest option, although not really flexible.

选项 1:只创建一个中间件是 Auth1 和 Auth2 的组合版本,用于检查 2 种用户类型。这是最简单的选择,虽然不是很灵活。

Option 2: since version 5.1middlewares can take parameters - see more details here: https://laravel.com/docs/5.1/middleware#middleware-parameters. You could implement a single middleware that would take list of user roles to check against and just define the allowed roles in your routes file. The following code should do the trick:

选项 2:由于5.1 版中间件可以接受参数 - 请在此处查看更多详细信息:https: //laravel.com/docs/5.1/middleware#middleware-parameters。您可以实现一个单一的中间件,该中间件将接受用户角色列表进行检查,并在您的路由文件中定义允许的角色。以下代码应该可以解决问题:

// define allowed roles in your routes.php
Route::group(['namespace' => 'Common', 'middleware' => 'checkUserRoles:role1,role2', function() {
  //routes that should be allowed for users with role1 OR role2 go here
}); 

// PHP < 5.6
// create a parametrized middleware that takes allowed roles as parameters
public function handle($request, Closure $next) {

  // will contain ['role1', 'role2']
  $allowedRoles = array_slice(func_get_args(), 2);

  // do whatever role check logic you need
}

// PHP >= 5.6
// create a parametrized middleware that takes allowed roles as parameters
public function handle($request, Closure $next, ...$roles) {

  // $roles will contain ['role1', 'role2']

  // do whatever role check logic you need
}

回答by ztvmark

This example How to pass multiple parameters to middleware with OR condition in Laravel 5.2

本例 Laravel 5.2 如何将多个参数传递给带有 OR 条件的中间件

Instead of adding multiple arguments to your handle method and having to update it every time you add a new role to your application, you can make it dynamic.

无需向您的 handle 方法添加多个参数,并且每次向应用程序添加新角色时都必须更新它,您可以使其动态化。

Middleware

中间件

 /**
 * Handle an incoming request.
 *
 * @param $request
 * @param Closure $next
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
 */
public function handle($request, Closure $next) {

    $roles = array_slice(func_get_args(), 2); // [default, admin, manager]

    foreach ($roles as $role) {

        try {

            Role::whereName($role)->firstOrFail(); // make sure we got a "real" role

            if (Auth::user()->hasRole($role)) {
                return $next($request);
            }

        } catch (ModelNotFoundException $exception) {

            dd('Could not find role ' . $role);

        }
    }

    Flash::warning('Access Denied', 'You are not authorized to view that content.'); // custom flash class

    return redirect('/');
}

Route

路线

Route::group(['middleware' => ['role_check:default,admin,manager']], function() {
    Route::get('/user/{user_id}', array('uses' => 'UserController@showUserDashboard', 'as' => 'showUserDashboard'));
});

This will check if the authenticated user has at least one of the roles provided and if so, passes the request to the next middleware stack. Of course the hasRole()method and the roles themselves will need to be implemented by you.

这将检查经过身份验证的用户是否至少具有提供的一个角色,如果是,则将请求传递给下一个中间件堆栈。当然,hasRole()方法和角色本身需要您自己实现。

You can use php 5.6

您可以使用 php 5.6

public function handle($request, Closure $next, ...$roles)
{
    foreach ($roles as $role) {

        try {
            if ($request->user()->can($role)) {
              return $next($request);
        }

        } catch (ModelNotFoundException $exception) {
          abort(403);
        }
    }

}