我使用policies进行用户授权。访客用户如何使用策略?
下面是我的代码:
在控制器中:
class PostController extends Controller
{
public function index(Post $post)
{
$this->authorize($post);
return $post->all();
}
}在策略中:
class PostPolicy
{
// This function executes only for authenticated users.
// I want to use it for guest users too
public function index(User $user)
{
return $user->can('get-posts');
}
}发布于 2016-09-04 18:38:07
我认为最简单的方法是使用Auth中间件进行保护。或检查策略中是否对用户进行了身份验证
发布于 2016-09-09 00:02:45
首先创建一个新的服务提供商:
php artisan make:provider GuestServiceProvider然后使用以下命令编辑GuestServiceProvider.php:
public function boot()
{
// Laravel policies only work if the user isn't null so for guest access we need to assign a dummpy user.
// From now on to check for guest use is_null(Auth::user()->getKey())
if(!Auth::check()) {
$userClass = config('auth.providers.users.model');
Auth::setUser(new $userClass());
}
}现在,策略将适用于访客用户,在您的策略中,您可以通过执行以下操作来检查访客:
if(is_null(Auth::user()->getKey())){
// it's a guest
}这本质上意味着如果用户没有id,那么它就不是一个真正的用户,因此必须是一个来宾。
发布于 2021-03-07 19:52:30
在您的PostPolicy中更改此设置
class PostPolicy{
// This function executes only for authenticated users.
// I want to use it for guest users too
public function index(User $user)
{
return $user->can('get-posts');
}
}至:
class PostPolicy{
// This function executes only for authenticated users.
// I want to use it for guest users too
public function index(?User $user)
{
return $user->can('get-posts');
}
}https://stackoverflow.com/questions/39315774
复制相似问题