【问题标题】:How to setup cancancan abilities如何设置 cancancan 能力
【发布时间】:2017-07-18 05:30:46
【问题描述】:

无法弄清楚如何使用康康康能力设置我的不同角色。我有一个模型“业务”,其中有许多用户,其角色为 :owner、:manager 或 :employee。
我试图首先表明,如果他们不属于该业务,他们将看不到该业务的任何内容。其次,我想根据他们的角色来限制功能。

我想我可以通过使用 if 语句在视图中执行此操作,并且只向他们显示他们可以访问的内容,但想知道是否有使用 cancan 的更好方法

【问题讨论】:

  • 您可以添加您尝试过但不起作用的代码吗?

标签: ruby-on-rails cancancan rolify


【解决方案1】:
  • 在你的能力范围内.rb

    class Ability
      include CanCan::Ability
    
      def initialize(user)
        alias_action :create, :read, :update, :destroy, :to => :crud
        if user
            if user.role == "manager"
                can :crud, Business, :id => user.business_id 
                # this will cek whether user can access business instance (id)     
            elsif user.role == "owner"
                can :manage, :all
            end
        end
      end
    end
    

在您的控制器内部,您可以通过 2 种方式进行检查

  1. 第 1 步:使用 load_and_authorize_resource,这将自动检查所有 7 个 rails 方法

    class BookingsController < ApplicationController
      load_and_authorize_resource 
      # this before filter will automatically check between users and resource
      # rails method here
      def show
      end
    end
    
  2. 第 2 步:在每个方法中使用授权手动检查

    def show
      @business = Business.find(params[:id])
      authorize! :read, @business
    end
    

【讨论】:

    【解决方案2】:

    一定要通读cancan's wiki,因为我不是 100% 了解这一点,但我认为解决方案看起来像这样:

    def initialize(user)
      user ||= User.new
    
      if user.has_role?(:owner)
        can :read, Business, Business.all do |business|
          business.id == user.business_id
        end
      elsif user.has_role?(:whatever)
        # etc
      end
    end
    

    然后用正常的cancan方式在控制器中检查authorize!。至于在视图中显示它们适当的功能,您可以在视图中执行一堆 if 语句,或者尝试使用部分使其看起来很可口,或者签入控制器并根据角色呈现不同的视图,但是,是的,某处必须有 if 语句。

    【讨论】:

      【解决方案3】:

      最好的方法是始终使用“增量”权限。考虑到 cancancan 已经假设您的用户对Business 没有权限,因此您可以根据他们的角色给予他们“增量”权限。

      一个例子是:

      # give read access if they have any role related to the business
      can :read, Business, users: { id: user.id }
      # give write access if they are manager
      can [:edit, :update], Business, business_users: { role: 'manager', user: { id: user.id } }
      # give destroy permissions to owners
      can [:destroy], Business, business_users: { role: 'owner', user: { id: user.id } }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-02
        • 2015-11-26
        相关资源
        最近更新 更多