关于laravel的用户授权
(一)定义策略类
//我们以文章授权为例 判断用户是否有用修改和删除权限
php artisan make:policy PostsPolicy
运行会生成一个文件夹 (Policies文件夹)
(二)注册策略类和模型关系
注册策略类,找到 AuthServiceProvider.php
,编写如下
protected $policies = [
'App\Posts' => 'App\Policies\PostPolicy'
];
绑定模型关系,打开 PostPolicy.php
文件,添加两个方法,首先引入 User
模型 和 Posts
模型
//用户修改文章权限 返回一个bool类型
public function update(User $user, Posts $post)
{
return $user->id == $post->user_id;
}
//删除文章权限
public function delete(User $user, Posts $post)
{
return $user->id == $post->user_id;
}
(三)策略判断
我们可以在编辑文章前判断该用户是否有权限,比如下面是我们文章的编辑和删除方法,我们加入授权验证
//编辑逻辑
public function update(Posts $post)
{
//验证
$this->validate(\request(),[
'title' => 'required|string|min:5|max:100',
'content' => 'required|string|min:10'
]);
//验证授权
$this->authorize('update', $post);
//逻辑
$post->title = \request('title');
$post->content = \request('content');
$post->save();
//渲染
return redirect("/posts/{$post->id}");
}
这样操作会报错,如果用户没有权限编辑和删除的话提交之后会报一个错误!
This action is unauthorized.
就是没有权限,我们可以搭配@can
和@endcan
来根据用户是否拥有权限,然后把编辑和删除按钮显示和隐藏,就可避免这个错误提示。
在模板中将按钮根据权限来区分显示和隐藏
<div style="display:inline-flex">
<h2 class="blog-post-title">{{ $post->title }}</h2>
@can('update', $post)
<a style="margin: auto" href="/posts/{{ $post->id }}/edit">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
@endcan
@can('delete', $post)
<a style="margin: auto" href="/posts/{{ $post->id }}/delete">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
@endcan
</div>
@can
和 @endcan
就等同于原生代码中的
//管理员权限
$admin_power = 'xx用户id';
<div style="display:inline-flex">
<h2 class="blog-post-title">{{ $post->title }}</h2>
<?php if ($admin_power) { ?>
<a style="margin: auto" href="/posts/{{ $post->id }}/edit">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
<?php } ?>
<?php if ($admin_power) { ?>
<a style="margin: auto" href="/posts/{{ $post->id }}/delete">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
<?php } ?>
</div>
这样就实现了一个用户授权的过程