簡體   English   中英

在 CanCan 中通過多個操作進行授權

[英]Authorize with multiple action in CanCan

在授權方面,我試圖更好地理解 CanCan 的功能。 想象一下這個控制器動作:

def update
  if can? :action, Model or can? :resolve, Model or can? :authorize, AnotherModel
    # My Code here
    respond_with @model
  else
    raise CanCan::AccessDenied.new(nil, :update, Model)
  end
end

我在嘗試使用authorize!找到上述問題的解決方案時達到了這一點authorize! . 據我所知(也在看簽名) authorize! 只接受一個權限(動作)和一個主題,帶有可選消息,如下所示:

def authorize!(action, subject, *args)
  # code
end

有沒有一種我可能會忽略的方法來指示授權檢查多個操作? 將兩個授權一個接一個地作為權限之間的AND條件,我希望它像OR條件一樣工作,基本上類似於上面的自定義代碼(在 CanCan 中存在提高AuthorizationNotPerformed的問題,可以避免使用skip_authorize_resource這不是我真正想做的事情)。

您可以創建自定義操作並根據需要創建任意數量的or

can :my_update_action, Project do |project|
  can?(:read, ModelX) || can?(:read, ModelY) || ... 
end

最后,我在能力類中添加了這個相當不錯的解決方案:

def multi_authorize!(*actions, message_hash)
    message = nil
    if message_hash.kind_of?(Hash) && message_hash.has_key?(:message)
      message = message_hash[:message]
    end
    auth = false
    actions.each do |act|
      auth = auth || can?(act[0], act[1])
    end
    if !auth
      message ||= unauthorized_message(actions[0][0], actions[0][1])
      raise CanCan::AccessDenied.new(message, actions[0][0], actions[0][1])
    end
end

包括控制器的助手:

module CanCanAddition
  def multi_authorize!(*args)
    @_authorized = true
    current_ability.multi_authorize!(*args)
  end
end

if defined? ActionController::Base
  ActionController::Base.class_eval do
    include ApplicationHelper::CanCanAddition
  end
end

我這樣稱呼它:

  def create
    multi_authorize! [:create, Model1], [:authorize, Model2], :message => "You are not authorized to perform this action!"
    # other code...
  end

警告:由於能力類中的代碼,您必須提供一條消息,否則最后一對授權將不會在*args傳遞。 我會花一些時間來克服這個問題,但我認為解決方案的想法很適合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM