Context aware authorization using CanCan

后端 未结 1 1245
迷失自我
迷失自我 2021-02-03 14:23

I want to use CanCan to handle my permissions. My site has many different permissions levels, and most of them are context aware. For instance, Here are the relations in my 3 ma

1条回答
  •  一向
    一向 (楼主)
    2021-02-03 14:49

    Ok, I solved the problem. My use case is briefly mentioned in the beginning of the CanCan README and I missed it. You can define new Ability classes in app/models/ that take in a different parameter other than current_user. To do so, you put the following in your controller:

    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
    

    Now you can create league_ability.rb in app/models/.

    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
    

    One thing to note is that this relies on your application controller calling a method in a child class. Hope that helps!

    0 讨论(0)
提交回复
热议问题