3

我正在尝试向已经存在的相当大的应用程序添加授权,但我必须稍微混淆细节。

这是背景:

在我们的应用程序中,我们有一个或多个分层的角色,大致如下:

BasicUser -> SuperUser -> Admin -> SuperAdmin

对于授权,每个用户模型实例都有一个对应于上述的属性“角色”。

我们有一个在 Backoffice 下命名的 RESTful 控制器“用户”。所以简而言之,它是 Backoffice::UsersController。

class Backoffice::UsersController < ApplicationController
  filter_access_to :all
  #... RESTful actions + some others
end

所以问题来了:

我们希望用户能够授予用户编辑用户的权限,但前提是他们的角色比他们当前拥有的“更小”。我在 authorization_rules.rb 中创建了以下内容

authorization do
  role :basic_user do
    has_permission_on :backoffice_users, :to => :index
  end
  role :super_user do
    includes :basic_user
    has_permission_on :backoffice_users, :to => :edit do
      if_attribute :role => is_in { %w(basic_user) }
    end
  end
  role :admin do
    includes :super_user
  end
  role :super_admin do
    includes :admin
  end
end

不幸的是,据我所知,这条规则似乎没有得到应用。

  1. 如果我将规则注释掉,没有人可以编辑
  2. 如果我保留规则,您可以编辑所有人

我还尝试了 if_attribute 的几种变体:

if_attribute :role => is { 'basic_user' }
if_attribute :role => 'basic_user'

他们得到相同的效果。有人有什么建议吗?

4

2 回答 2

4

我确定您现在已经解决了这个问题,但我们刚刚遇到了类似的问题,并找到了一个可能会有所帮助的解决方案。纯粹在声明性授权 DSL 中可能无法处理这种情况,但您可以利用 DSL 在您的模型和视图中做正确的事情。基本上,我们需要访问角色层次图。

线索是 declarative_authorization 有一个漂亮的控制器,它会生成一个显示角色层次结构的图表。使用他们拥有的相同支持代码,您可以轻松访问任何角色的祖先:

class Role < ActiveRecord::Base
  require 'declarative_authorization/development_support/analyzer'

  has_many :assignments
  has_many :users, :through => :assignments

  validates :name, :presence => true
  validates :name, :uniqueness => true

  def ancestors
    Authorization::DevelopmentSupport::AnalyzerEngine::Role.for_sym(self.name.to_sym, 
      Authorization::Engine.instance).ancestors.map { |r| r.instance_variable_get("@role") }
  end

  def self_and_ancestors
    ancestors << self.name.to_sym
  end
end

然后,您可以使用它来做一些事情,例如仅在用户编辑器中提供与 current_user 的角色相同或次等的角色选择,并拒绝访问或不允许对试图不当提升用户的人更改模型。在声明性授权 DSL 本身的上下文中,它并不是很有用,因为它需要首先被解析,从而创建一种循环引用。

希望这可以帮助任何需要它的人。

于 2011-03-03T09:20:23.823 回答
0

我的应用程序中有以下方法并且它有效

role :super_user do
    includes :basic_user
    has_permission_on :backoffice_users do
      to :edit
      if_attribute :role => is {"basic_user"}
    end
end
于 2010-05-18T16:16:18.953 回答