1

我为我的 laravel 项目创建了一些权限和角色。

web.php路由中,我可以使用一些权限定义这样的中间件:

$can = ['can:manage_global,manage_users,create_users'];
$this->get('/create', 'UserController@create')->middleware($can);

或在获得一项许可的刀片中:

@can('manage_global')
   ...
@endcan

如何检查刀片和控制器线中的多个权限值web.php

4

2 回答 2

2

你可以写中间件。

class CanAnyMiddleware
{
    public function handle($request, Closure $next, $permissions)
    {
        foreach ($permissions as $permission) {
            if ( $request->user()->can($permission)) {
                return $next($request); // allow
            }
        }

        return redirect(route('home')); // deny
    }
}

并在路由字符串中使用它。

Route::get('/create', 'UserController@create')
    ->middleware('canAny:manage_global,manage_users,create_users');

从 Laravel 5.6 开始,你可以@canany在 Blade 中使用:

@canany(['manage_global', 'manage_users', 'create_users'])
    ...
@endcanany

https://github.com/laravel/framework/pull/24137

于 2018-12-05T14:40:44.023 回答
0

如果您尝试检查用户是否可以从控制器访问您定义的任何门,您可以从现有的Authorizable 特征中获取一个队列,并在您自己的特征中添加一些额外的功能。

<?php

namespace App\Traits\MyAuthorizable;

use Illuminate\Contracts\Auth\Access\Gate;

trait MyAuthorizable {
  public function canAny(array $abilities, $arguments = []) {
    return collect($abilities)->reduce(function($canAccess, $ability) use ($arguments) {
      // if this user has access to any of the previously checked abilities, or the current ability, return true
      return $canAccess || app(Gate::class)->forUser($this)->check($ability, $arguments);
    }, false);
  }

  public function canAll(array $abilities, $arguments = []) {
    return collect($abilities)->reduce(function($canAccess, $ability) use ($arguments) {
      // if this user has access to _all_ of the previously checked abilities, _and_ the current ability, return true
      return $canAccess && app(Gate::class)->forUser($this)->check($ability, $arguments);
    }, true);
  }
}

use App\ MyAuthorizable;您可以在您的用户类定义中将此特征添加到您的用户类中。

这将为您的用户公开canAnycanAll方法,然后您可以从控制器访问它们。

<?php

public function get($request) {
    $User = Auth::User();

    if ($User->canAll(['manage_global', 'manage_users', 'create_users'])) {
        // user can do all of the things
    } elseif ($User->canAny(['manage_global', 'manage_users', 'create_users']) {
        // user can only do _some_ of the things
    } else {
        // user can do _none_ of the things
    }
}
于 2018-12-05T15:16:35.480 回答