设计和当前用户
我已设置 Devise 来管理我的应用程序的身份验证。
我有一个类别模型,用户可以在其中创建自己的类别。用户 has_many :类别。该模型具有 user_id 属性,因此当有人登录并转到类别/索引时,查询将使用 current_user.id 从控制器引入类别,以过滤出要引入的类别。
到目前为止,一切顺利并且运行良好,似乎没有人能够看到其他人的类别,但说实话,除非我错过了一些东西,否则这似乎有点不安全。我怎么知道某些黑客不会弄清楚并发送自己的修改参数的请求?
这是可能的还是我偏执?另外,我可能没有正确使用该功能?
I've set up Devise to manage the authentication to my app.
I have a Category model in which users create their own categories. User has_many :categories. This model has a user_id attribute, so when someone logs in and goes to categories/index for example, from the controller the query would bring categories using current_user.id to filter out which ones to bring.
So far straight forward and works well, nobody seems to be able to see someone else's categories, but to be honest, unless I'm missing something, this seems a bit insecure. How do I know some hacker will not figure it out and send his own requests modifying the params?
Is this possible or am I being paranoid? Also, I might not be using the functionality properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您在
users
和categories
之间使用正确的关系,即您应该能够在控制器中使用类似的内容:
这样您就可以使用当前用户无论传递什么参数,它都只会获取他们的画廊。您不再通过可能不安全的 user_id 进行搜索。
如果您担心某人能够查看不属于他们的类别,您可以添加自己的私有方法,类似于
:authenticate_user!
以确保正在显示或编辑的类别确实属于到当前用户,像其他用户一样在 before_filter 中运行它,如果他们没有权限则重定向。Provided you're using the proper relationship between
users
andcategories
, i.e.you should be able to use something like this in your controller:
This way you're using the current user regardless of what parameters may be passed, and it will only get their galleries. You're not searching by a potentially insecure user_id anymore.
If you're worried about someone being able to view a category that isn't theirs, you can add your own private method similar to
:authenticate_user!
to make sure that the category being shown or edited actually belongs to the current user, running it in a before_filter like the other one, and redirecting if they don't have permission.我认为您的关系设置是一对一(每个用户一个类别)而不是一对多(每个用户多个类别)。如果您的
User
模型中有一个category_id
,则您应该进行以下设置。如果您希望每个用户有多个类别,那么我建议使用带有
user_id
和category_id
的链接表(如模型UserCategory
)。然后,在您的
Category
控制器中,您可以使用上面的代码来获取给定用户的所有类别。I think you have the relationship setup for a one-to-one (one category per user) instead of a one-to-many (many categories per user). If you have a
category_id
in theUser
model, the following should be your setup.If you want to have multiple categories per user, than I suggest using a link table (as model
UserCategory
) withuser_id
andcategory_id
.Then, in your
Category
controller you can use your code from above to grab all categories by a given user.根据乔什的回答,我只是将其变成了 if else 语句。我将
params[:id]
转换为整数,因为current_user.id
返回 1。Based on Josh's answer, I just made it into an if else statement. I converted
params[:id]
to integer sincecurrent_user.id
returns one.