我正在关注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();
//
}
}
web.php:
Route::resource('projects', 'ProjectsController')->middleware('can:touch,project');
ProjectsController.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错误。我根本不知道发生了什么。