在 Railscasts 中 Episode 388 - Multitenancy with Scopes , Ryan 正在添加默认范围以确保安全:
Alternatively we can use an authorization library such as CanCan to handle the scoping but this isn’t designed for a multi-tenant apps and it won’t solve this problem very well. This is one case where it’s acceptable to use a default scope so that’s what we’ll do.
class Tenant < ActiveRecord::Base
attr_accessible :name, :subdomain
has_many :topics
end
class Topic < ActiveRecord::Base
attr_accessible :name, :content
belongs_to :user
has_many :posts
default_scope { where(tenant_id: Tenant.current_id) }
end
我的问题是:我想实现授权(例如使用 Cancan)并想定义如下能力:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, Topic
else
can :read, Topic
end
end
end
用户是否有能力管理所有租户的主题,还是只能在租户范围内管理?
或者一个更普遍的问题: Multi-Tenancy 应用程序的正确授权方法是什么?
最佳答案
使用 CanCan 或 CanCanCan 您走在正确的 rails 上我认为,因为 CanCan 已被弃用。
我不喜欢 default_scope
因为它不是 threadsafe .用户 ID 存储在一个类变量中,这意味着您的应用程序中的两个或多个并发用户将打破此设置,除非您使用 Unicorn或其他一些网络服务器,确保不会有超过一个客户端连接访问同一个线程。
因此,您应该使用类似 Cancan 的东西。
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
# User's own Topics only:
can :manage, Topic, user_id: user.id
# or, with a Tenant
can :manage, Topic, tenant_id: user.tenant.id if user.tenant # User belongs_to Tenant
can :manage, Topic, tenant_id: user.tenants.map(&:id) if user.tenants.any? # User has_many Tenants
else
can :read, Topic # Anyone can read any topic.
end
end
end
从以上三个示例中选择您需要的策略。
编辑 针对@JoshDoody 在评论中的问题的 Multi-Tenancy 管理员稍微复杂的示例:
class Admin < User; end
class TenantAdmin
belongs_to :tenant
belongs_to :admin, class_name: User
end
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, Topic, tenant_id: TenantAdmin.where(admin: user).map(&:tenant_id)
else
can :read, Topic # Anyone can read any topic
end
end
end
现在,这可能没有您想要的那样高效,但一般的想法是您有 TenantAdmins,他们将能够管理其租户中的主题。
希望这对您有所帮助。
关于ruby-on-rails - Multi-Tenancy 应用程序中的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311344/