0

In a demo application we want to handle tenants in different schemas (default apartment configuration for Postgres). These are to be selected from the subdomain of the application url.

I got it working, but then broke it again (it started using public instead of the selected schema).

I could narrow the problem down to this: If I use the following piece of code everything works as expected:

require 'apartment/elevators/first_subdomain'
Rails.application.config.middleware.use Apartment::Elevators::FirstSubdomain
Apartment::Elevators::FirstSubdomain.excluded_subdomains = ['demo', 'localhost']

If I do this myself (extending the missing Tenant behavior to return a 404), it doesn't work anymore:

class DemoUserSelectionMiddleware < Apartment::Elevators::Generic
  def parse_tenant_name(request)
    subdomain = request.host.split('.')[0]
    unless Rails.application.config.is_demo && subdomain.start_with?('demo_')
      'public'
    else
      subdomain
    end
  end

  def call(*args)
    begin
      super
    rescue Apartment::TenantNotFound
      Rails.logger.error "ERROR: Apartment Tenant not found: #{Apartment::Tenant.current.inspect}"
      return [404, {"Content-Type" => "application/json"}, ["Error" => "Tenant not found"]]
    end
  end
end

No error, no log entries, nothing. It just decides to use 'public'. Using byebug I see that the subdomain is properly found.

Am I missing something obvious here?

estani
  • 24,254
  • 2
  • 93
  • 76

1 Answers1

0

In the first snippet, you added demo subdomain to excluded_subdomains. In other words, public tenant should be active with demo subdomain. In other subdomains, the corresponding tenants will be active.

In the piece of code you wrote, public tenant doesn't active with demo subdomain. On the contrary, public tenant is active in all subdomains.

.
.
unless Rails.application.config.is_demo && subdomain.start_with?('demo_')
.
.

Looks like there's a logical error here. I think you should use if instead of unless.

demir
  • 4,591
  • 2
  • 22
  • 30
  • The logic is correct, it will be public **unless** we are on demo and de subdomain is demo_.*. As I said I did debug it, so I know the two pieces of code return what I expect them. But as I said, Apartment is falling back to 'public' (which apartment does under certain circumstances, but I can't see why in here) – estani Aug 06 '19 at 08:38