如何检查用户是否有权在 Laravel 中访问此功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52651119/
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
How to check if user has permission to access this function in Laravel
提问by Ahmed essam
I have a function that check if the user has permission or not and it return Boolean.
我有一个函数来检查用户是否有权限并返回Boolean。
Question is
问题是
How I check in each function user has permission or not. For example in users controllerI have 2 functions:
我如何签入每个功能用户是否有权限。例如在用户控制器中,我有两个功能:
- index(): show all users
- delete($id): delete a single user
- index():显示所有用户
- delete($id): 删除单个用户
index():
指数():
public function index () {
if(Auth::user() -> hasPermissionTo('show all users')) {
// continue for API
} else {
// response with error for API
}
}
I know that there is a better way to do that because I don't want to repeat this if statement in all my functions.
我知道有更好的方法来做到这一点,因为我不想在我的所有函数中重复这个 if 语句。
What I have tried to do:
我试图做的事情:
I have tried to create a helper function that check if user has permission and return the response error if the user doesn't have permission. And call it in every function but it didn't work.
我试图创建一个帮助函数来检查用户是否有权限,如果用户没有权限则返回响应错误。并在每个函数中调用它,但它不起作用。
Helper function code:
辅助功能代码:
if(!function_exists('userHasPermission')) {
function userHasPermission ($permission) {
$main_permission = 'do everything';
if (!Auth::user() -> hasPermissionTo($main_permission) || !Auth::user() -> hasPermissionTo($permission)) {
$res = trans('api_responses.authorization_failed');
return Response::json([
'message' => $res['message'],
'code' => $res['code']
], $res['code']);
}
}
}
index function call
索引函数调用
public function index()
{
// PERMISSIONS CHECK
userHasPermission('users show active');
$getUsers = $this -> users -> getAllActive();
return Response::json($getUsers);
}
But it never returns the error response even if the user doesn't have permission and even it entered the if statement in my helper!
但它永远不会返回错误响应,即使用户没有权限,甚至它在我的助手中输入了 if 语句!
采纳答案by Peter
With Laravel you can use a gate for this.
使用 Laravel,您可以为此使用门。
In you App\Providers\AuthServiceProvider file do something like this:
在你的 App\Providers\AuthServiceProvider 文件中做这样的事情:
public function boot()
{
$this->registerPolicies();
Gate::define('do-everything', function ($user) {
return $user->hasPermission('do-everything');
});
Gate::define('do-one-thing', function ($user) {
return $user->hasPermission('do-one-thing');
});
}
And then in your controller:
然后在您的控制器中:
if (Auth::user()->can('do-everything')) {
// the user can do everything
}
if (Auth::user()->can('do-one-thing')) {
// the user can just do one thing
}
or
或者
if (!Auth::user()->can('do-everything')) {
abort(403);
}
// user has permission to the everything from here on
or in your routes/web.php you could do this:
或者在你的 routes/web.php 你可以这样做:
Route::get('/things', 'ThingController@action')->middleware(['can:do-one-thing']);
or you can group the routes like this:
或者您可以像这样对路线进行分组:
Route::middleware(['can:do-everything'])->group(function () {
Route::get('/things', 'ThingController@index');
Route::get('/other-things', 'OtherThingController@index');
...
}
You can also look at https://laravel.com/docs/5.7/authorizationfor more ideas.
您还可以查看https://laravel.com/docs/5.7/authorization以获取更多想法。
回答by Ahmed Nour Jamal El-Din
Your helper function returns a new response but it returns it to the controller not as HTTP response, so You can get the returned value like this:
您的辅助函数返回一个新的响应,但它不是作为 HTTP 响应将其返回给控制器,因此您可以像这样获得返回值:
public function index()
{
// PERMISSIONS CHECK
$response = userHasPermission('users show active');
$getUsers = $this -> users -> getAllActive();
return Response::json($getUsers);
}
So what you need is to check the response if it has a value but with this approach you are going to have the same problem as your first one.
因此,您需要检查响应是否具有值,但是使用这种方法,您将遇到与第一个相同的问题。
To solve it: throw exception from the helper function instead of returning some response.
解决方法:从辅助函数抛出异常而不是返回一些响应。
A better solutionis to use FormRequest, check this linkto do it, be sure to check "Authorizing Form Requests" section which states the authorize function.
更好的解决方案是使用 FormRequest,检查这个链接来做,一定要检查“授权表单请求”部分,其中说明了授权功能。
EDIT:
编辑:
what you have to do is the following:
你需要做的是以下几点:
create new class let's call it "IndexRequest" that inherits from "FormRequest" class, then implement authorize method.
创建新类让我们称其为继承自“FormRequest”类的“IndexRequest”,然后实现授权方法。
so something like this:
所以像这样:
class IndexRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return Auth::user() -> hasPermissionTo('show all users');
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
];
}
}
then in your method:
然后在你的方法中:
public function index(IndexRequest $request)
{
$getUsers = $this -> users -> getAllActive();
return Response::json($getUsers);
}
you don't have to check it manually, Laravel will do it for you using "authorize" function of IndexRequest class.
您不必手动检查它,Laravel 会使用 IndexRequest 类的“授权”功能为您完成。
回答by Mostafa Khedeer
This way to check multi permissions to decide sho
这种检查多权限的方式来决定sho
@php
$patients_menu_item=0;
$users_menu_item=0;
$roles_menu_item=0;
if(Auth::user() -> hasPermissionTo('Patient Add')||Auth::user() -> hasPermissionTo('Patients List')) {
$patients_menu_item=1;
}
if(Auth::user() -> hasPermissionTo('User Add')||Auth::user() -> hasPermissionTo('Users List')) {
$users_menu_item=1;
}
if(Auth::user() -> hasPermissionTo('Role Add')||Auth::user() -> hasPermissionTo('Roles List')) {
$roles_menu_item=1;
}
@endphp
@if($patients_menu_item == 1)
<li class="has-sub">
<a>
<i class="ft-users"></i><span class="menu-title">Patients</span>
</a>
<ul class="menu-content">
@can('Patient Add')
<li>
<a href="{{url('patients/register')}}"
class="menu-item">Register Patient</a>
</li>
@endcan
@can('Patients List')
<li>
<a href="{{url('patients/index')}}"
class="menu-item">{{ trans('website.Show Patients') }}</a>
</li>
@endcan
</ul>
</li>
@endif