【发布时间】:2016-06-11 12:36:28
【问题描述】:
假设我有一个场景,我们有Users,每个用户都可以创建自己的Projects。
我正在尝试将我的 Rails 控制器的 Show 操作限制为仅允许管理员或项目所有者通过 Show 操作。
我面临的问题是,也许我对如何在 Pundit 中使用 Scopes 有误解。
我的Show 操作如下所示:
def show
project = policy_scope(Project).find_by({id: project_params[:id]})
if project
render json: project
else
render json: { error: "Not found" }, status: :not_found
end
end
我的 Pundit Scope 类如下所示:
class Scope < Scope
def resolve
if @user.admin?
scope.all
else
# obviously, if non-matching user id, an ActiveRelation of
# empty array would be returned and subsequent find_by(...)
# would fail causing my controller's 'else' to execute
# returning 404 instead of 403
scope.where(user_id: @user.id)
end
end
end
在我的 Rails 测试中,我试图断言非项目所有者应该收到 403 禁止:
test "show project should return forbidden if non admin viewing other user's project" do
# "rex" here is not the owner of the project
get project_path(@project.id), headers: @rex_authorization_header
assert_response :forbidden
end
我的测试失败了。我收到错误消息:
Failure:
ProjectsControllerTest#test_show_project_should_return_forbidden_if_non_admin_viewing_other_user's_project [/Users/zhang/App_Projects/LanceKit/Rails_Project/LanceKit/test/controllers/projects_controller_test.rb:40]:
Expected response to be a <403: forbidden>, but was a <404: Not Found>.
Expected: 403
Actual: 404
我不太觉得我在正确使用 Pundit。
我应该使用 Pundit 的 authorize project 而不是使用 policy_scope(Project)... 来执行 Show 操作吗?
我期待 scope.where(...) 检测到错误的用户 ID 并返回一些错误,说“您无权查看此资源”而不是返回结果。
【问题讨论】:
-
我还发现了这个 Stackoverflow 帖子:stackoverflow.com/questions/21172620/… Rob 的回答似乎建议使用范围进行索引/显示操作。
标签: ruby-on-rails pundit