【问题标题】:Context aware authorization using CanCan使用 CanCan 的上下文感知授权
【发布时间】:2011-08-18 04:24:39
【问题描述】:

我想使用 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 是 Leagues 的嵌套资源。我想要做的是允许用户修改联赛,并根据存储在 League_relation 中的数据来衡量每个用户的授权。然后,我希望用户仅根据存储在用户模型中的数据来修改联赛关系。

简而言之:我基本上希望 LeagueRelations 用于授权 League 动作,而 Users 用于授权 LeagueRelations 动作。即league_relation.owner = true 删除一个联赛,但 user.owner?必须为真才能删除 LeagueRelation。如何在联赛控制器内部根据league_relation的属性进行授权,并在其他模型上授权其他控制器中的其他动作。如果您需要更多说明,请发表评论。

谢谢。

【问题讨论】:

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


    【解决方案1】:

    好的,我解决了这个问题。我的用例在 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      相关资源
      最近更新 更多