Design for User hierarchy in Ruby on Rails
I have an application that requires authentication, and have a User model. There are 4 levels of authorisation with the following rules:
- Level 1 users can create/edit/delete all level 2,3 and 4 users.
- Level 2 us开发者_StackOverflow中文版ers can create level 3 and 4 users, and edit only those users they own.
- Levels 3 and 4 have no authorisation to create/edit/delete users.
- UPDATE: Level 3 and 4 users could have multiple level 2 parent users.
In addition to this, I want all users to be able to login through a single interface.
Are there any patterns for dealing with such a hierarchy? using an authorisation plugin such as cancan will allow me to define the different levels of authorisation, but not the relationships between the different users.
Essentially I would like a design that would enable me to write controller code such as this:
@level_two_users = current_user.find_all_my_level_two_users
Thanks
You could add a attribute level
to your user model and a method to query for allowed users.
To get all users with level X just use a query like User.find_all_by_level(2)
class User
attr_accessible :level
def allowed_to_edit_user?(user)
case self[:level]
when 1
user.level > 1
when 2
user.level > 2 && user.created_by?(self)
end
false
end
def allowed_to_create_user_with_level?(level)
self[:level] <= 2 && self[:level] < level
end
end
Btw. who creates level 1 users? ;-)
精彩评论