check if id is in array of ids from recursive method

31 views
Skip to first unread message

Johan Hovda

unread,
Feb 21, 2012, 4:58:14 AM2/21/12
to declarative_authorization
Hi!

I have found Declarative Authorization to be very useful, using it on
a site with dynamic roles.

I have a resource database where resources can belong to different
locations. Users and groups (self-referential user table) can have
different roles on different locations. Groups can be inside other
groups. Authorization works well for single users using 'if_attribute'
to check if the location_id is among the location_ids that the user is
allowed to show, edit, etc.:

has_permission_on :locations do
to [:show, :new, :create, :edit, :update, :destroy]
if_attribute :id => is_in { (user.permissions.where(:role =>
"admin").collect {|i|
Location.find_by_id(i.location_id).subtree_ids}.flatten.uniq )}
end

Since the groups can be "nested" inside each other, I have figured
that I'll have to use a recursive method to find all the "legal"
location ids. I tried this:

has_permission_on :locations do
to [:show, :new, :create, :edit, :update, :destroy]
if_attribute :id => is_in { (user.permissions.where(:role =>
"admin").collect {|i| Location.find_by_id(i.location_id).subtree_ids}
+ find_group_location_ids(user)).flatten.uniq }
end

with the method defined outside the 'authorization do'-routine:

def find_group_location_ids(user)
location_ids = []
nested_group_location_ids(user)
def nested_group_location_ids(user)
user.group_memberships.each do |gm|
location_ids = location_ids + gm.user.location.id
nested_group_location_ids(gm.user)
end
end
return location_ids
end

The problem is that the method call doesn't find the method. I get
this error:

NoMethodError (undefined method `find_group_location_ids' for
(<Authorization::Engine::AttributeValidator:0x7fb63448e2b0>)

I have tried to place the method definition on a lot of different
places, but with the same result.

How can I use if_attribute to see if an id is inside an array from a
recursive method?

Is there another way to solve my problem?


Yours,


Johan Hovda

Steffen Bartsch

unread,
Mar 5, 2012, 4:49:48 PM3/5/12
to declarative_...@googlegroups.com
Am 21.02.2012 10:58, schrieb Johan Hovda:
> I have tried to place the method definition on a lot of different
> places, but with the same result.
>
> How can I use if_attribute to see if an id is inside an array from a
> recursive method?

Why not place it in the User model, if necessary as a class method? You
won't be able to call a method inside auth_rules.rb.

Steffen

Johan Hovda

unread,
Apr 2, 2012, 11:51:44 AM4/2/12
to declarative_...@googlegroups.com
Thank's!

Haven't had time to try it out earlier. 

After reading your answer, it seems so obvious. Things aren't so easy when you don't understand what you're doing! :-)


Johan
Reply all
Reply to author
Forward
0 new messages