permissions - 如何检查我的控制器中的权限
问题描述
我是 Laravel 的新手,我正在自己编写一个用户管理系统。此时,
- 我可以 CRUD 权限、角色和用户,
- 我可以通过 AuthServiceProvider@boot 方法检查权限,如下所示:
public function boot()
{
Gate::before( function (User $user , $permission) {
// App administrator
if($user->getPermissions()->contains('appAll'))
{
return true;
}
// Permission check
return $user->getPermissions()->contains($permission);
});
}
在我的 AdminUserController 中,我可以像这样检查权限:
public function index()
{
if( Gate::check('createUser') || Gate::check('readUser') || Gate::check('updateUser') || Gate::check('deleteUser')) {
return view('userMgmt/users/index', [
'users' => User::getUsersWithRolesWithTexts()
]);
}
else
{
return redirect(route('home'))->withErrors('You do not have required permission');
}
}
那运作良好。
但是这是包装每个控制器方法的正确方法:
if( Gate::check(...) ...) {
//Do what the method is supposed to do
}
else
{
return redirect(route('SOME.ROUTE'))->withErrors('FUCK ALL');
}
如果有人能给我一些想法,那就太好了。保护你
解决方案
有一个名为authorize的控制器辅助函数,您可以从扩展的控制器中的任何方法调用它App\Http\Controllers\Controller
。该方法接受动作名称和模型,如果用户没有被授权,它会抛出异常。因此,代替if...else
语句,它将是一行:
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// The current user can update the blog post...
}
推荐阅读
- transparency - c# WinForms中的透明FlowLayoutPanel
- google-apps-script - 在 Google AppScript 中使用 Web3?
- postgresql - Spring Boot App 无法使用来自 Kubernetes 机密的凭据访问 PostgreSQL
- r - 文本挖掘时单词被截断
- r - GLMM:glmer()中的自由度校正和随机残差方差
- javascript - 使用下拉列表中的属性值过滤对象数组 - Angular 模板
- android - 如何在 react native 中制作聊天框?
- javascript - 处理动态地图内容(标记)的正确方法
- javascript - 如何从两个元素中获取文本,将它们转换为数字并将它们添加到柏树中?
- python - 调试python代码(VSCODE)时终端出错