Skip to content

Instantly share code, notes, and snippets.

@ang3lkar
Created July 15, 2016 09:00
Show Gist options
  • Save ang3lkar/363f8b718a1753af3a826c9286fbeee2 to your computer and use it in GitHub Desktop.
Save ang3lkar/363f8b718a1753af3a826c9286fbeee2 to your computer and use it in GitHub Desktop.
Rails middleware to enforce subdomain requests
# app/middleware/subdomain_enforcer.rb
class SubdomainEnforcer
def initialize(app)
@app = app
end
def call(env)
@request = Rack::Request.new(env)
if @request.params['sbd'].present?
new_location = get_new_location(@request.params['sbd'])
log_redirect(new_location)
[301, { 'Location' => new_location }, ['Moved Permanently']]
else
@status, @headers, @response = @app.call(env)
[@status, @headers, self]
end
end
def each(&block)
@response.each(&block)
end
private
def get_new_location(subdomain)
uri = URI(@request.url)
uri.host = "#{subdomain}.#{uri.host}"
params = CGI.parse(uri.query || '')
params.delete('sbd')
uri.query = URI.encode_www_form(params)
uri.to_s.gsub(/\?$/, '')
end
def log_redirect(url)
Rails.logger.info "[sans_subdomain_link] method=#{@request.request_method} url=#{@request.url} redirect_to=#{url}"
end
end
# test/middleware/subdomain_enforcer_test.rb
require 'test_helper'
require 'rack'
class SubdomainEnforcerTest < ActiveSupport::TestCase
setup do
@app = lambda do |params|
[200, {}, ""]
end
end
test 'redirects to url with subdomain with params if sbd param is present' do
request = Rack::MockRequest.env_for "https://workable.com/backend?sbd=winterfell&force_desktop=true"
response = SubdomainEnforcer.new(@app).call(request)
assert_equal 301, response[0]
assert_equal({ 'Location' => 'https://winterfell.workable.com/backend?force_desktop=true' }, response[1])
assert_equal(['Moved Permanently'], response[2])
end
test 'redirects to url with subdomain if sbd param is present' do
request = Rack::MockRequest.env_for "https://workable.com/backend?sbd=winterfell"
response = SubdomainEnforcer.new(@app).call(request)
assert_equal 301, response[0]
assert_equal({ 'Location' => 'https://winterfell.workable.com/backend' }, response[1])
assert_equal(['Moved Permanently'], response[2])
end
test 'forwards request if sbd param is missing' do
request = Rack::MockRequest.env_for "https://workable.com/backend?force_desktop=true"
response = SubdomainEnforcer.new(@app).call(request)
assert_equal 200, response[0]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment