Object Based Authorization

I need to restrict users from interacting with objects that do not
belong_to them (reference their id). For example, user #2 should not be
able to load the page /events/show/3 if Event #3 has a user_id of ‘1’.
Anyone know of a clean solution for this at the controller level?

In the events controller add the following

:before_filter :do_something_checking, :only=>[:show]

do_something_checking is a method in the events controller that
perform checking whether id is belong to the logged in user, and
redirect to the warning page.

On Oct 10, 1:07 pm, Peter M. [email protected]

Peter M. wrote:

I need to restrict users from interacting with objects that do not
belong_to them (reference their id). For example, user #2 should not be
able to load the page /events/show/3 if Event #3 has a user_id of ‘1’.
Anyone know of a clean solution for this at the controller level?

The built-in Rails association finds are your best bet.

In this example URL:
/objects/show/23

The controller might look like…

user = User.find(session[:user_id])
object = Object.find(params[:id])

If someone changes the ID in the URL, you have problems. However…

user = User.find(session[:user_id])
user.objects.find(params[:id])

Automatically searches for objects with the specified ID AND belong to
the user.

Jamis has an excellent write up on this… but I can’t find it. =( But
here’s his website:
http://weblog.jamisbuck.org/

Daniel W. wrote:

My mistake, it was Koz over at the Rails Way:
http://www.therailsway.com/2007/3/26/association-proxies-are-your-friend

Great suggestion and great link. Thanks Daniel. I ran into another
problem however (and it looks like others have on the article’s
discussion thread). I can’t seem to get this to work with a :through
association. Using my initial example, if User has_many :participants,
:through => :events, I can’t use current_user.participants without
getting a LocalJumpError ‘no block given’.

Anyone know a way around this?

Daniel W. wrote:

The built-in Rails association finds are your best bet.
Automatically searches for objects with the specified ID AND belong to
the user.

Jamis has an excellent write up on this… but I can’t find it. =( But
here’s his website:
http://weblog.jamisbuck.org/

My mistake, it was Koz over at the Rails Way:
http://www.therailsway.com/2007/3/26/association-proxies-are-your-friend

Not sure about your specific issue. However there is a lot of good
info about many to many relationships on Josh S.'s blog,
http://blog.hasmanythrough.com/

-Jamal