Class: MultiTenantSubdomain::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/multi_tenant_subdomain/middleware.rb

Overview

This middleware is used to set the current tenant based on the subdomain of the request.

It is used to ensure that all requests are scoped to a single tenant.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



9
10
11
# File 'lib/multi_tenant_subdomain/middleware.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/multi_tenant_subdomain/middleware.rb', line 13

def call(env)
  subdomain = extract_subdomain(env)
  tenant = MultiTenantSubdomain.config.tenant_model_table.classify.constantize.find_by(subdomain: subdomain)

  if tenant.nil? && subdomain.present?
    # Option 1: Return a 404 Not Found response
    return [404, {'Content-Type' => 'text/html'}, ['Tenant not found']]

    # Option 2: Redirect to main domain (uncomment to use)
    # main_domain = env['HTTP_HOST'].split('.').drop(1).join('.')
    # return [302, {'Location' => "https://#{main_domain}"}, []]
  end

  MultiTenantSubdomain::TenantManager.current_tenant = tenant
  @app.call(env)
ensure
  # IMPORTANT: Reset the tenant after the request is processed
  # This ensures that the tenant is not shared between requests
  MultiTenantSubdomain::TenantManager.reset_tenant
end