开发者

Design for User hierarchy in Ruby on Rails

开发者 https://www.devze.com 2023-03-05 20:00 出处:网络
I have an application that requires authentication, and have a User model. There are 4 levels of authorisation with the following rules:

I have an application that requires authentication, and have a User model. There are 4 levels of authorisation with the following rules:

  1. Level 1 users can create/edit/delete all level 2,3 and 4 users.
  2. Level 2 us开发者_StackOverflow中文版ers can create level 3 and 4 users, and edit only those users they own.
  3. Levels 3 and 4 have no authorisation to create/edit/delete users.
  4. 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? ;-)

0

精彩评论

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

关注公众号