Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

security - Rails - Separate Database per Subdomain

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is some code I use for this very problem:

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

Website.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

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...