0

我有用户、帐户和角色模型。Role存储Account和User之间的关系类型。

我留空attr_accessibleRole防止出现批量分配漏洞(否则攻击者可能会更改角色类型——所有者、管理员等……、帐户或用户 ID)。

但是,如果管理员想将订阅者更改为版主怎么办?这将引发批量分配安全异常:

user = User.find(params[:id])
role = user.roles.find_by_account_id(params[:account_id])
role.type = "admin"

我该如何解决这个问题?一种方法是创建一个单独的模型来表示每个角色(所有者、管理员、版主、订阅者)并使用 STI 类型模式。这让我可以:

user = User.find(params[:id])
user.moderatorship.build(account_id: params([:account_id])

乏味!我必须创建 Onwership、Moderatorship、Subscribership 等......,并让它们从 Role 继承。如果我想坚持单一的角色模型,我怎样才能拥有动态角色而不让自己暴露于批量分配漏洞?

额外的问题:我应该使用用户 has_many 角色(用户可以为每种角色类型拥有一条记录)还是 has_one 角色(用户只能拥有一个角色记录,如果他们的角色发生变化必须切换)模式?

class User < ActiveRecord::Base
  attr_accessible :name, :email
  has_many :accounts, through: roles
end

class Account < ActiveRecord::Base
  attr_accessible :title
  has_many :users, through: roles
end

class Role < ActiveRecord::Base
  attr_accessible
  belongs_to: :user
  belongs_to: :account
end
4

2 回答 2

2

您可以将“as”与 attr_accessible 一起使用,以获得不同的分配能力。例如,

attr_accessible :type, as: :admin

然后,当您进行批量分配时,您可以执行类似的操作

@role.update_attributes {type: :moderator}, as: :admin # Will update type
@role.update_attributes {type: :moderator} # Will not update type
于 2012-04-29T21:05:29.830 回答
1

最灵活的方法是覆盖mass_assignment_authorizer模型类中的方法以动态更改可访问属性。

例如:

class Article < ActiveRecord::Base
  attr_accessible :name, :content
  attr_accessor :accessible

  private
  def mass_assignment_authorizer
    super + (accessible || [])
  end
end

现在你可以这样使用它:

@article.accessible = [:important] if admin?

此示例来自RailsCast #237,您可以在其中了解有关此方法的更多信息。


此外,我想向您推荐可以帮助您处理角色和能力的CanCan gem。

于 2012-04-29T21:21:23.593 回答