Dania02525/apartmentex

Tenant schema as subdomain

shulhi opened this issue · 4 comments

I checked out the widget_saas project for sample of using apartmentex. Is there a way to have the tenant schema as the subdomain? Something like this: https://django-tenant-schemas.readthedocs.io/en/latest/ i.e. http://first-tenant.example.com instead of http://example.com/tenant/:first_tenant_id.

I think this is irrelevant. In both cases (subdomain vs url path) you'd need to write some plug that checks either subdomain or url path to get the tenant name on each request.

@shulhi this is all I did:

defmodule App.TenantController do
  plug :set_current_tenant

  defp set_current_tenant(conn, _params) do
    {"host", host} = List.keyfind(conn.req_headers, "host", 0)
    tenant = Tenant.get_by_host!(host)
    assign(conn, :current_tenant, tenant)
  end
end

defmodule App.Tenant do
  def get_by_host!(host) do
    subdomain = host
      |> String.split(".")
      |> Enum.take(1)
      |> Enum.join(".")

    Repo.get_by!(__MODULE__, subdomain: subdomain)
  end
end

To add to the advice above, the tenant qualification can really come from anywhere- subdomain, path, jwt claim, some other header, etc. basically anything you can access in plug on a request can be used to target a schema

Thanks, I got it working with plug.