implement locomotivecms/engine#785: redirect to the main domain when there are several domains

did committed Oct 21, 2015
commit 4d6bdc1aee43453e52c00e19e6e3087f9f730233
Showing 3 changed files with 49 additions and 5 deletions
locomotive/steam/entities/site.rb b/lib/locomotive/steam/entities/site.rb +7 -5
@@ @@ -6,11 +6,13 @@ module Locomotive::Steam
def initialize(attributes = {})
super({
- cache_enabled: false,
- prefix_default_locale: false,
- updated_at: nil,
- content_version: nil,
- template_version: nil
+ cache_enabled: false,
+ prefix_default_locale: false,
+ updated_at: nil,
+ content_version: nil,
+ template_version: nil,
+ domains: [],
+ redirect_to_first_domain: false
}.merge(attributes))
end
locomotive/steam/middlewares/site.rb b/lib/locomotive/steam/middlewares/site.rb +15 -0
@@ @@ -15,6 +15,8 @@ module Locomotive::Steam
# log anyway
log_site(site)
+
+ redirect_to_first_domain_if_enabled(site)
end
private
@@ @@ -38,6 +40,19 @@ module Locomotive::Steam
end
end
+ def redirect_to_first_domain_if_enabled(site)
+ # the site parameter can be an instance of Locomotive::Steam::Services::Defer and
+ # so comparing just site may not be reliable.
+ if site.try(:redirect_to_first_domain) && site.domains.first != request.host
+ klass = request.scheme == 'https' ? URI::HTTPS : URI::HTTP
+ redirect_to klass.build(
+ host: site.domains.first,
+ port: [80, 443].include?(request.port) ? nil : request.port,
+ path: request.path,
+ query: request.query_string.present? ? request.query_string : nil).to_s
+ end
+ end
+
def log_site(site)
if site.nil?
msg = "Unable to find a site, url asked: #{request.url} ".colorize(color: :light_white, background: :red)
spec/unit/middlewares/site_spec.rb +27 -0
@@ @@ -40,4 +40,31 @@ describe Locomotive::Steam::Middlewares::Site do
end
+ describe 'redirection to the first domain' do
+
+ let(:redirect_to_first_domain) { false }
+ let(:url) { 'http://acme.com' }
+ let(:site) { instance_double('SiteWithDomains', name: 'Acme', domains: ['www.acme.com', 'acme.com'], redirect_to_first_domain: redirect_to_first_domain) }
+
+ before { expect(services).to receive(:current_site).and_return(site) }
+
+ it { is_expected.to eq [200, nil] }
+
+ describe 'option enabled' do
+
+ let(:redirect_to_first_domain) { true }
+
+ it { is_expected.to eq [301, 'http://www.acme.com/'] }
+
+ context 'first domain requested' do
+
+ let(:url) { 'http://www.acme.com' }
+ it { is_expected.to eq [200, nil] }
+
+ end
+
+ end
+
+ end
+
end