开发者

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.

I'm wondering if there is a mo开发者_运维技巧re 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.


CanCan is another gem that offers authorization functionality. It's all managed in one ruby file and can then be incorporated into controllers with one line. There's also a number of view helpers so you can use <% if can? :update, @article %> in your views.


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. 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. 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.

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

See this:

  • Checking permissions when no user is signed in

  • Checking permissions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜