nathanl / authority

*CURRENTLY UNMAINTAINED*. Authority helps you authorize actions in your Rails app. It's ORM-neutral and has very little fancy syntax; just group your models under one or more Authorizer classes and write plain Ruby methods on them.
MIT License
1.21k stars 67 forks source link

Can you add an example for a controller's index action that includes filtering by user? #54

Closed Altonymous closed 11 years ago

Altonymous commented 11 years ago

I have an application where I need to limit the index on a controller to only return items that a user created. Right now I can't figure out how to use this gem to do that. It appears that I am still required to do something like..

current_user.widgets.all

I'd rather just set it up to apply permissions to filter the widgets and then do Widgets.all. In this way I don't have to worry about anyone forgetting filter the widgets to only current_user.

nathanl commented 11 years ago

Authority can't change the way that Widget.all works. You could do Widget.all.select {|widget| widget.readable_by?(current_user)}, but that's loading everything into memory and would be very poor-performing. If you know that each widget has a creator and that's the basis of the permissions, current_user.widgets would be much more efficient, since it filters in SQL.

There are a couple of things you can authorize here:

However, if you don't do current_user.widgets, you're going to present them with a list of widgets that include some they aren't supposed to see.

Personally, I do use current_user.widgets for the index action and recommend it.

Altonymous commented 11 years ago

I am trying to remove access control from my controllers and have it enforced in the background (in my case it's now in the models as a mixin module). I found a gem that can help me with that. It uses scopes to filter things before the query is made and then gives access to the user and resource after the fact for further checks if warranted.

The current_user model works in very basic applications, but in my case it's just not enough.

Thanks for the response! At least I know now!

nathanl commented 11 years ago

Are you referring to https://github.com/plataformatec/has_scope?

Altonymous commented 11 years ago

No this one: https://github.com/inossidabile/protector

nathanl commented 11 years ago

Interesting. I'm not sure I understand the usage difference, though. Don't you still have to do this in your controller?

Widget.restrict!(current_user)

You can't just use Widget.all, right?

nathanl commented 11 years ago

Closing unless you want to discuss this further.