【发布时间】:2019-10-28 15:17:10
【问题描述】:
我正在尝试使用 laravel 策略来检查故事是否“可见”,如果不是,则经过身份验证的用户是否拥有该故事(在这种情况下,他仍然可以查看它)。我使用
设置我的策略php artisan make:policy StoryPolicy --model=Story
在那里我设置了查看经过身份验证的用户是否可以看到故事所需的检查
<?php
namespace App\Policies;
use App\User;
use App\Story;
use Illuminate\Auth\Access\HandlesAuthorization;
class StoryPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the story.
*
* @param \App\User $user
* @param \App\Story $story
* @return mixed
*/
public function view(User $user, Story $story)
{
if ($story->visibility == 'visible') {
return true;
} else {
return $story->user_id == $user->id;
}
}
}
我在我的 AuthServiceProvider 中注册了策略
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Story' => 'App\Policies\StoryPolicy'
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
}
}
据我了解,我应该能够在我的控制器中使用此策略。我就是这么做的。
<?php
namespace App\Http\Controllers;
use App\Storyblock;
use App\User;
use Illuminate\Http\Request;
use App\Category;
use App\Story;
class StoryController extends Controller
{
public function __construct(){
$this->middleware('auth')->except('show');
}
// GET shows the story page
public function show(Story $story) {
$this->authorize('view',$story);
return view('story.show', compact('story'));
}
}
然而这总是导致 403
我已经尝试了很多事情,改变了政策的设置方式,如果一切都正确的话,也会改变逻辑。经过 4 小时的在线查找后,我未能找到答案。
另外,在我的 phpStorm 中,我注意到我的策略文件显示为红色,并且在整个项目中都没有使用。这让我觉得我无法在我的 AuthServiceProvider 中导入它们
【问题讨论】:
-
此时您可以忽略 IDE 所说的内容,如果没有运行时信息,它无法知道很多内容,尤其是考虑到对 Policy 类的唯一引用是通过字符串
标签: php laravel laravel-5.7