2010-04-19 126 views
3

我試圖給一個已經存在的相當大的應用程序添加授權,但我必須混淆一下細節。對角色的declarative_authorization權限

這裏的背景:

在我們的應用程序,我們有一個是分層的數字或角色,大致是這樣的:

BasicUser -> SuperUser -> Admin -> SuperAdmin 

若需授權每個用戶模型實例有一個屬性「角色」這對應於以上。

我們有一個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' 

並且它們獲得相同的效果。有人有任何建議嗎?

回答

0

我在我的應用程序下面的方法和它的作品

role :super_user do 
    includes :basic_user 
    has_permission_on :backoffice_users do 
     to :edit 
     if_attribute :role => is {"basic_user"} 
    end 
end 
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本身的上下文中並不是很有用,因爲它需要先解析,創建一種循環引用。

希望這可以幫助那些需要它的人。