简体   繁体   English

Ruby on Rails以更优雅的方式来验证用户只能编辑自己的内容

[英]Ruby on rails more elegant way to authenticate that users can edit only their own content

I currently authenticate that users can edit their own content only by: 我目前正在验证用户只能通过以下方式编辑自己的内容

@posts = current_user.posts.find(params[:id])

Is there an easier way to do this across all controllers? 有没有更简单的方法可以在所有控制器上做到这一点?

I have a before_filter that requires a user must be logged in, but it doesn't check who the individual user is. 我有一个before_filter,要求用户必须登录,但是它不检查单个用户是谁。

I'm wondering if there is a more elegant solution that would just require one edit to the before_filer method rather than putting a current_user method before every model that needs protecting. 我想知道是否有一个更优雅的解决方案,只需要对before_filer方法进行一次编辑,而不是将current_user方法放在每个需要保护的模型之前。

CanCan is another gem that offers authorization functionality. CanCan是另一个提供授权功能的宝石。 It's all managed in one ruby file and can then be incorporated into controllers with one line. 所有这些都在一个ruby文件中进行管理,然后只需一行即可合并到控制器中。 There's also a number of view helpers so you can use <% if can? :update, @article %> 还有许多视图助手,因此可以使用<% if can? :update, @article %> <% if can? :update, @article %> in your views. <% if can? :update, @article %>在您的视图中。

I worked with a framework at some point that let you put mandatory conditions in find queries, but I don't think this is (natively) possible with Rails. 我在某个时候使用了一个框架,该框架可以让您在查询中添加强制条件,但是我认为Rails不可能(本来)做到这一点。 Possibly with a plugin. 可能带有插件。

However, sometimes you will want to query beyond the context of a single user, so you'd need a way to override that, possibly with the :except parameter of the before_filter. 但是,有时您将需要查询单个用户的上下文以外的内容,因此您需要一种方法来覆盖它,可能使用before_filter的:except参数。 But then you'd have to remember current_user on the things in the excepted methods that do need to be user-specific, and forgetting to specify it could be very dangerous. 但是然后,您必须记住current_user在例外方法中确实需要针对用户的事情,而忘记指定它可能非常危险。

You could save a little typing for the vast majority of cases by overriding the model's Find functionality somehow, but you're also going to make the exceptions extremely ugly and potentially dangerous. 通过以某种方式覆盖模型的“查找”功能,您可以在绝大多数情况下节省一些键入内容,但是您还将使异常变得极为丑陋,并可能带来危险。

Have you checked out aegis? 你检查过宙斯盾了吗? If you are not willing to code something by hand then you can check out aegis. 如果您不愿意手工编码,则可以检查盾牌。 Meets your requirements. 符合您的要求。 It has extensive documentation too. 它也有大量的文档。 http://github.com/makandra/aegis http://github.com/makandra/aegis

See this: 看到这个:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM