我目前正在尝试将inherited_resources和authority集成到我的Rails应用程序中。
我有点纠结于检查基于资源执行控制器操作的能力的最佳位置。以下代码在authority中作为示例给出:
def edit
@llama = Llama.find(params[:id])
authorize_action_for(@llama) # Check to see if you're allowed to edit this llama. failure == SecurityViolation
end
def update
@llama = Llama.find(params[:id])
authorize_action_for(@llama) # Check to see if you're allowed to edit this llama.
@llama.attributes = params[:llama] # Don't save the attributes before authorizing
authorize_action_for(@llama) # Check again, to see if the changes are allowed.
if @llama.save?
# etc
end因为在inherited_resources中查找器是抽象的,所以我认为将authorise_action_for检查也添加到这些抽象的查找器上会很好。
注意在update (假设是create)的情况下授权机构的双重检查。
发布于 2013-07-19 17:41:20
我依靠ActiveSupport::Concern来简化模块。我将我的关注点存储在app下一个名为concerns的目录中。我将其称为inherited_resources_with_authority.rb,您可能需要在application.rb中修改您的autoload_paths,以便从该文件夹加载文件。
module InheritedResourcesWithAuthority
extend ActiveSupport::Concern
included do
inherit_resources
authorize_actions_for :resource_class
alias_method_chain :resource, :authority
alias_method_chain :build_resource, :authority
alias_method_chain :update_resource, :authority
end
protected
def resource_with_authority
resource_without_authority
authorize_action_for(get_resource_ivar)
end
def build_resource_with_authority
build_resource_without_authority
authorize_action_for(get_resource_ivar)
end
def update_resource_with_authority(object, attributes)
object.assign_attributes(*attributes)
authorize_action_for(object)
object.save
end
end我们基本上是链接重要的inherited_resources抽象方法,并在必要的地方插入我们的授权代码。最后一个是最棘手的,因为我们不能调用我们链接的原始方法,所以我们必须在这里复制一些inherited_resources的代码。
要使用这个关注点,只需从控制器调用include InheritedResourcesWithAuthority即可。
注意,你不能使用在你的控制器上激活inherited_resources的类继承方法,因为我们已经在这个问题中使用了另一个方法。
完整内容请点击此处:https://coderwall.com/p/tp5sig
建议绝对受欢迎:D
https://stackoverflow.com/questions/16350935
复制相似问题