我正在关注 laracasts 5.7 系列,并且正在使用策略进行授权部分。当我第一次添加它时它工作正常。但是第二天当我再次打开应用程序(没有触摸任何代码)时,我一直被抛出 403 错误。这种情况已经发生了两次。起初我只是以为我搞砸了代码。所以我再次重做了整个策略授权。但是第二次,我在保存代码之前确保一切正常。然后同样的事情发生了。到目前为止,这是我的代码:ProjectPolicy.php:
public function touch(User $user, Project $project)
{
return $project->owner_id == $user->id;
}
AuthServiceProvider.php:
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
'App/Project' => 'App\Policies\ProjectPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
网页.php:
Route::resource('projects', 'ProjectsController')->middleware('can:touch,project');
项目控制器.php:
use App\Project;
use Illuminate\Http\Request;
class ProjectsController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::where('owner_id', auth()->id())->get();
return view('projects.index', ['projects' => $projects]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validated = request()->validate([
'title' => 'required',
'description' => ['required','min:5']
]);
$validated['owner_id'] = auth()->id();
Project::create($validated);
return redirect('/projects');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Project $project)
{
// $this->authorize('update', $project);
// abort_if($project->owner_id !== auth()->id(), 403);
// $this->authorize('touch', $project); // from ProjectPolicy
// abort_if( \Gate::denies('touch', $project), 403);
return view('projects.show', ['project' => $project]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', ['project' => $project]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Project $project)
{
$project->update(request(['title','description']));
return redirect()->action(
'ProjectsController@show', ['id' => $project->id]
);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect('/projects');
}
}
需要明确的是:它在前一天晚上工作,第二天当我打开应用程序时,即使我根本没有编辑代码,它仍然让我陷入 403 错误。我根本不知道发生了什么。