Rails 3限制访问权限,因此用户只能更新其数据 [英] Rails 3 Limiting Access so user can update only their data

查看:145
本文介绍了Rails 3限制访问权限,因此用户只能更新其数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎应该是相当简单的东西,因为它将需要很多。我检查用户是否登录正常,但一旦用户登录,他们可能会改变其他人的帐户。例如:说,ID为1的用户已登录,他们将/ users / 2 /编辑为网址。这将显示用户2s数据,并允许他们修改它。当然,我可以改变控制器中的编辑操作使用像这样...

This seems like something that should be fairly simple since it would be needed a lot. I check to see if a user is logged in fine but once a user is logged in they could potentially alter other peoples accounts. For example: say user with ID 1 was logged in and they put /users/2/edit as the url. This would show them user 2s data and allow them to modify it. Of course I can alter the edit action in the controller to use something like this...

  def edit
    @user = User.find(current_user.id)
  end

控制器,所以用户总是那个谁登录。这是很好,如果你只有一对夫妇控制器与几个动作,但可能是一个痛苦,如果你有很多。看起来应该有一种方法来限制这个全局,所以用户只能更新自己的数据,无论他们使用什么动作或控制器。

where current_user is set in the controller so the user is always that person who is logged in. This is fine if you only have a couple controllers with a couple actions but could be a pain if you have many. It seems like there should be a way to limit this globally so the user can only update their own data no matter what action or controller they use.

有办法

推荐答案

我认为您的问题是关于如何执行授权。此外,我怀疑你可能是conflatingbelongs_to模型关联名称与授权。 belongs_to关联名称描述了一个模型与另一个模型的关系,但它并不意味着应用程序如何控制对任何模型的访问。

I think your question is really about how to do authorization. Also, I suspect you might be conflating the "belongs_to" model association name with authorization. The "belongs_to" association name describes how one model relates to another, but it does not imply anything about how an application controls access to any model.

Hishalv是正确的,使用控制器过滤器是管理授权的正确方法。这是正确的MVC方式。给予 Rails指南一个好的阅读,以便您理解。

Hishalv is correct that using a controller filter is the right way to manage authorization. It's the correct MVC way. Give the Rails Guide a good read so you understand that.

然后,您可以考虑使用像CanCan这样的授权gem,或者根据Hishalv的建议滚动您自己的。 Cancan可以与Devise等认证宝石配合使用。如果你做自己的,把一个帮助方法放在ApplicationController中是一个简单的事情,并写成它的工作方式,无论模型。

Then, you can consider using an authorization gem like CanCan, or rolling your own per Hishalv's suggestion. CanCan works well in tandem with an authentication gem like Devise. If you do roll your own, it's a simple thing to put a helper method in ApplicationController and write it in such a way that it works regardless of the model.

这篇关于Rails 3限制访问权限,因此用户只能更新其数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆