Sha256: 8f55c9a9d8cb41829a78fcdb19e0aa1a296788b0e8293d1d1f9e0ee70fcfd5ed

Contents?: true

Size: 1.33 KB

Versions: 44

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module Decidim
  # A middleware that enhances the request with the current organization based
  # on the hostname.
  class CurrentOrganization
    # Initializes the Rack Middleware.
    #
    # app - The Rack application
    def initialize(app)
      @app = app
    end

    # Main entry point for a Rack Middleware.
    #
    # env - A Hash.
    def call(env)
      organization = detect_current_organization(env)
      if organization
        env["decidim.current_organization"] = organization
        @app.call(env)
      else
        organization = find_secondary_host_org(env)
        return @app.call(env) unless organization

        location = new_location_for(env, organization.host)

        [301, { "Location" => location, "Content-Type" => "text/html", "Content-Length" => "0" }, []]
      end
    end

    private

    def detect_current_organization(env)
      host = host_for(env)
      Decidim::Organization.find_by(host: host)
    end

    def find_secondary_host_org(env)
      host = host_for(env)
      Decidim::Organization.find_by("? = ANY(secondary_hosts)", host)
    end

    def host_for(env)
      Rack::Request.new(env).host.downcase
    end

    def new_location_for(env, host)
      request = Rack::Request.new(env)
      url = URI(request.url)
      url.host = host
      url.to_s
    end
  end
end

Version data entries

44 entries across 44 versions & 1 rubygems

Version Path
decidim-core-0.11.2 app/middleware/decidim/current_organization.rb
decidim-core-0.12.0.pre app/middleware/decidim/current_organization.rb
decidim-core-0.11.1 app/middleware/decidim/current_organization.rb
decidim-core-0.11.0.pre1 app/middleware/decidim/current_organization.rb