使用CanCan进行上下文感知授权

时间:2011-08-18 04:24:40

标签: ruby-on-rails ruby ruby-on-rails-3 cancan

我想使用CanCan来处理我的权限。我的网站有许多不同的权限级别,其中大多数都是上下文感知的。例如,以下是我的3个主要模型中的关系:

class User < ActiveRecord::Base
  has_many :league_relations
  has_many :leagues, :through => :league_relations
end

class League < ActiveRecord::Base
  has_many :league_relations
  has_many :users, :through => :league_relations
end

class LeagueRelation < ActiveRecord::Base
  belongs_to :user
  belongs_to :league
end

注意,LeagueRelations是联赛的嵌套资源。我想要做的是允许用户修改联赛,并根据存储在league_relation中的数据来衡量每个用户的授权。然后,我希望用户仅根据存储在用户模型中的数据来修改联盟关系。

简洁:我基本上希望使用LeagueRelations来授权联盟行动,并使用User来授权LeagueRelations行动。即league_relation.owner = true删除联盟,但是user.owner?必须为true才能删除LeagueRelation。如何在联盟控制器内部基于league_relation的属性进行授权,并在其他模型上的其他控制器中授权其他操作。如果您需要更多说明,请发表评论。

感谢。

1 个答案:

答案 0 :(得分:10)

好的,我解决了这个问题。我在CanCan README的开头简要提到了我的用例,我错过了它。您可以在app / models /中定义新的Ability类,它们接受除current_user之外的其他参数。为此,您将以下内容放入控制器中:

def current_ability 
  if params[:controller] == 'leagues'
    @current_ability = LeagueAbility.new(current_user_league_relation)
  elsif params[:controller] == 'league_relations'
    @current_ability = LeagueRelationAbility.new(current_user_league_relation)
  else
    @current_ability = Ability.new(current_user)
  end
end

现在你可以在app / models /中创建league_ability.rb。

class LeagueAbility
  include CanCan::Ability

  def initialize(league_relation)
    league_relation ||= LeagueRelation.new

    if league_relation.owner?
      can :manage, League, :id => league_relation.league_id
    elsif league_relation.moderator?
      can :manage, League, :id => league_relation.league_id
      cannot [:delete, :destroy], League
    else
      can :read, League
      can :create, League
    end    
  end
end

需要注意的一点是,这依赖于应用程序控制器调用子类中的方法。希望有所帮助!