我为laravel项目创建了一些权限和角色。
在web.php
路线中,我可以使用一些权限来定义这样的中间件:
$can = ['can:manage_global,manage_users,create_users'];
$this->get('/create', 'UserController@create')->middleware($can);
或在具有一项许可的刀片服务器中:
@can('manage_global')
...
@endcan
如何检查刀片服务器和控制器行web.php
中的多权限值?
答案 0 :(得分:0)
您可以编写中间件。
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开始,您可以在Blade中使用@canany
:
@canany(['manage_global', 'manage_users', 'create_users'])
...
@endcanany
答案 1 :(得分:0)
如果您要检查用户是否可以从控制器访问您定义的任何门,则可以从现有的Authorizable trait中获取一个队列,并在自己的特征中添加一些其他功能。
<?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;
将此特征添加到用户类中。
这将为您的用户公开canAny
和canAll
方法,然后可以从您的控制器访问它们。
<?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
}
}