Rails - 每个子域的单独数据库 [英] Rails - Separate Database per Subdomain

查看:14
本文介绍了Rails - 每个子域的单独数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即将开始编写一个 Rails 应用程序,该应用程序将允许客户拥有一个单独的子域来访问我们的应用程序.从数据安全的角度考虑,如果每个客户端的访问权限都真正限制在他们的数据库中就好了,这样,如果生产代码中存在错误,他们将只能访问自己的数据库,而不能访问任何其他的数据库客户.

I am about to begin writing a Rails application that will allow clients to have a separate subdomain for their access to our application. Thinking from a data security standpoint, it would be nice if each client's access was truly limited to their database, that way, if there is a bug in production code, they would only be able to access their own database and not that of any other clients.

我知道如何做我想做的事情背后的代码,但我想知道是否有我可能缺少的更简单的解决方案.您将如何保护客户数据,以便在出现错误或黑客威胁时,他们的数据不太可能泄露?

I know the code behind how to do what I want, but I was wondering if there was a simpler solution that I might be missing. How would you go about securing client data so that in the event of a bug or hacker threat, their data would be less likely to be exposed?

推荐答案

这是我用来解决这个问题的一些代码:

Here is some code I use for this very problem:

application_controller.rb

application_controller.rb

before_filter :set_database

helper_method :current_website

# I use the entire domain, just change to find_by_subdomain and pass only the subdomain
def current_website    
  @website ||= Website.find_by_domain(request.host)
end

def set_database
  current_website.use_database
end

# Bonus - add view_path
def set_paths
  self.prepend_view_path current_website.view_path unless current_website.view_path.blank?
end

网站.rb

def use_database
  ActiveRecord::Base.establish_connection(website_connection)
end

# Revert back to the shared database
def revert_database
  ActiveRecord::Base.establish_connection(default_connection)
end

private

# Regular database.yml configuration hash
def default_connection
  @default_config ||= ActiveRecord::Base.connection.instance_variable_get("@config").dup
end

# Return regular connection hash but with database name changed
# The database name is a attribute (column in the database)
def website_connection
  default_connection.dup.update(:database => database_name)
end

希望这有帮助!

这篇关于Rails - 每个子域的单独数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆