如何防止访问属于不同用户的记录
如何防止基于会话变量访问特定的记录集?
即我有一个带有 user_id 键的项目表,如何根据 user_id 过滤对项目的访问。我不希望有人能够访问 /items/3/edit ,除非该项目有其用户 ID(基于会话变量)
更新: 我正在使用 @fl00r 建议的答案,进行一项更改,使用 find_by_id() 而不是 find(),因为它返回 nil 并且可以很好地处理:
@item = current_user.items.find_by_id([params[:id]]) || item_not_found
其中 item_not_found 在应用程序控制器中处理,只会引发路由错误。
How do I prevent accessing a specific set of records based on a session variable?
i.e. I have a table of items with a user_id key, how do I filter access to the items based on user_id. I don't want someone to be able to access /items/3/edit unless that item has their user id against it (based on session var)
update:
I am using the answer suggested by @fl00r with one change, using find_by_id() rather than find() as it returns a nil and can be handled quite nice:
@item = current_user.items.find_by_id([params[:id]]) || item_not_found
where item_not_found is handled in the application controller and just raises a routing error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过
current_user
对象获取项目来限制访问(User
应该:has_many => :items
),其中
current_user
是一种User.find(session[:user_id])
UPD
有用的 Railscast: http://railscasts.com/episodes/178-seven-security-tips,提示#5
Restrict access by fetching items through your
current_user
object (User
should:has_many => :items
)where
current_user
is kind ofUser.find(session[:user_id])
UPD
Useful Railscast: http://railscasts.com/episodes/178-seven-security-tips, TIP #5
您可以在show/edit/update方法中检查访问权限:
并添加restrict_access方法,例如在application_controller中
You can check access in show/edit/update method:
and add restrict_access method, for example in application_controller