我已经使用API资源构建了一个仅API应用程序,并使用Passport进行身份验证。该应用程序执行以下操作
使用邮递员,应用程序按预期工作,但更新和删除操作除外。如果用户尝试更新不属于他们的书,我想要返回错误响应。不幸的是,我获得了200 Ok状态代码而不是我的自定义消息和403状态代码。删除也是一样的。
这是我的BookController更新和删除方法
public function update(Request $request, Book $book)
{
// Update book if the logged in user_id is the same as the book user_id
if ($request->user()->id === $book->user_id) {
$book->update($request->only(['title', 'author']));
return new BookResource($book);
} else {
response()->json(['error' => 'You do not have the permission for this operation'], 403);
}
}
public function destroy(Request $request, Book $book)
{
// Delete book only if user_id matches book's user_id
if ($request->user()->id === $book->user_id) {
$book->delete();
return response()->json(null, 204);
} else {
response()->json(['error' => 'You do not have the permission for this operation'], 403);
}
}
注意:在邮递员中进行测试时,我只需在标题授权字段中添加承载标记即可。当用户拥有该书但当该书不归登录用户所有时获得200而不是403状态代码时起作用。
我做错了什么,我该如何解决?
您似乎没有在else
语句中返回您的响应 - 您可以像这样简化它:
public function update(Request $request, Book $book)
{
// Update book if the logged in user_id is the same as the book user_id
if ($request->user()->id === $book->user_id) {
$book->update($request->only(['title', 'author']));
return new BookResource($book);
}
return response()->json([
'error' => 'You do not have the permission for this operation'
], 403);
}
public function destroy(Request $request, Book $book)
{
// Delete book only if user_id matches book's user_id
if ($request->user()->id === $book->user_id) {
$book->delete();
return response()->json(null, 204);
}
return response()->json(['error' => 'You do not have the permission for this operation'], 403);
}
我还建议可能会研究政策 - 并将它们作为中间件应用到路线https://laravel.com/docs/5.7/authorization#writing-policies