如何在Ruby / Rails中清理用户权限代码?

时间:2017-11-01 22:24:55

标签: ruby-on-rails ruby

我正在编写一个系统,每个用户都可以管理其他用户的权限。

我有一个业务要求,即logged_in_user无法在排名中降级高于他们的人。我的立场如下:

STAFF < MANAGER < ORGANIZATION_ADMIN

我正在尝试为用户显示权限按钮,并使用以下(丑陋)方法完成工作,但感觉就像糟糕的代码。

# Iterate through all users and allow for their permissions to be modified
other_users.each do |other_user|
  buttons_to_show = get_buttons_to_show(logged_in_user, other_user)

  if buttons_to_show.include?(ORGANIZATION_ADMIN)
    puts "Make other_user #{ORGANIZATION_ADMIN}" # Will be a button on UI

  if buttons_to_show.include?(MANAGER)
    puts "Make other_user #{MANAGER}" # Will be a button on UI

  if buttons_to_show.include?(STAFF)
    puts "Make other_user #{STAFF}" # Will be a button on UI
end


def get_buttons_to_show(current_user, other_user)
  buttons_to_show = []

  if (current_user.at_least_staff? && other_user.role != MANAGER && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << STAFF
  end

  if (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << MANAGER
  end

  if current_user.at_least_organization_admin?
    buttons_to_show << ORGANIZATION_ADMIN
  end

  buttons_to_show
end                

2 个答案:

答案 0 :(得分:1)

你有没有看过像https://github.com/CanCanCommunity/cancancan这样的东西?

我最近使用它,你最终在这些模型中添加了一些代码:

if user.has_role? :uam_officer
  can :create, Segment
  cannot :approve, User
  cannot :reject, User
end

然后在视图中:

<% if can?(:create, Segment) %>
   <%= link_to 'New', new_management_segment_path, { :class=>"btn btn-primary" } %>
<% end %>

它有助于保持授权逻辑的整齐打包。

答案 1 :(得分:0)

我决定使用Pundit并将所有这些方法移到我的策略中。像魅力一样,更清洁。