Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow using domains in tenants #5007

Merged
merged 2 commits into from
Dec 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ Rails/DurationArithmetic:
Rails/DynamicFindBy:
Enabled: true
Whitelist:
- find_by_domain
- find_by_slug_or_id
- find_by_slug_or_id!
- find_by_manager_login
Expand Down
20 changes: 20 additions & 0 deletions app/assets/javascripts/admin/tenants/form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
(function() {
"use strict";
App.AdminTenantsForm = {
initialize: function() {
var form = $(".admin .tenant-form");
var inputs = $("input[name$='[schema_type]']", form);
var label = $("label[for$='schema']", form);

inputs.on("change", function() {
label.text(label.data("schema-type-" + $(this).val()));
});

inputs.each(function() {
if ($(this).is(":checked")) {
$(this).trigger("change");
}
});
}
};
}).call(this);
1 change: 1 addition & 0 deletions app/assets/javascripts/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ var initialize_modules = function() {
}
App.AdminBudgetsWizardCreationStep.initialize();
App.AdminMachineLearningScripts.initialize();
App.AdminTenantsForm.initialize();
App.AdminVotationTypesFields.initialize();
App.BudgetEditAssociations.initialize();
App.BudgetHideMoney.initialize();
Expand Down
10 changes: 1 addition & 9 deletions app/assets/stylesheets/admin/budgets/form.scss
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,12 @@
}

> fieldset {
border-top: 4px solid $admin-border-color;
@include admin-fieldset-separator;
clear: both;
margin-top: $line-height * 1.5;

&:first-of-type {
margin-top: 0;
}

legend {
color: $admin-text;
font-size: $small-font-size;
font-weight: bold;
padding-right: $line-height / 2;
text-transform: uppercase;
}
}
}
19 changes: 19 additions & 0 deletions app/assets/stylesheets/admin/tenants/form.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
.admin .tenant-form {
> fieldset {
@include admin-fieldset-separator;
margin-top: $line-height;
}

.radio-and-label {
display: flex;
margin-bottom: $line-height / 3;

&:last-of-type {
margin-bottom: $line-height * 2 / 3;
}

input {
margin-bottom: 0;
}
}
}
12 changes: 12 additions & 0 deletions app/assets/stylesheets/mixins/forms.scss
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,15 @@
%public-form {
@include public-form;
}

@mixin admin-fieldset-separator {
border-top: 4px solid $admin-border-color;

> legend {
color: $admin-text;
font-size: $small-font-size;
font-weight: bold;
padding-right: $line-height / 2;
text-transform: uppercase;
}
}
16 changes: 14 additions & 2 deletions app/components/admin/tenants/form_component.html.erb
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
<%= form_for [:admin, tenant] do |f| %>
<%= form_for [:admin, tenant], html: { class: "tenant-form" } do |f| %>
<%= render "shared/errors", resource: tenant %>

<%= f.text_field :name %>
<%= f.text_field :schema %>

<fieldset>
<legend><%= attribute_name(:url) %></legend>
<div class="radio-and-label">
<%= f.radio_button :schema_type, :subdomain, label: t("admin.tenants.form.use_subdomain", domain: domain) %>
</div>
<div class="radio-and-label">
<%= f.radio_button :schema_type, :domain, label: t("admin.tenants.form.use_domain") %>
</div>

<%= f.text_field :schema, label_options: { data: schema_labels_per_schema_type } %>
</fieldset>

<%= f.submit %>
<% end %>
16 changes: 16 additions & 0 deletions app/components/admin/tenants/form_component.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,20 @@ class Admin::Tenants::FormComponent < ApplicationComponent
def initialize(tenant)
@tenant = tenant
end

private

def attribute_name(attribute)
Tenant.human_attribute_name(attribute)
end

def domain
Tenant.default_domain
end

def schema_labels_per_schema_type
Tenant.schema_types.keys.to_h do |schema_type|
[:"schema_type_#{schema_type}", attribute_name(schema_type)]
end
end
end
2 changes: 2 additions & 0 deletions app/components/admin/tenants/index_component.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<tr>
<th><%= attribute_name(:name) %></th>
<th><%= attribute_name(:schema) %></th>
<th><%= attribute_name(:url) %></th>
<th><%= t("admin.shared.actions") %></th>
</tr>
</thead>
Expand All @@ -16,6 +17,7 @@
<tr id="<%= dom_id(tenant) %>">
<td><%= tenant.name %></td>
<td><%= tenant.schema %></td>
<td><%= tenant.host %></td>
<td>
<%= render Admin::TableActionsComponent.new(tenant, actions: [:edit]) do |actions| %>
<%= actions.action(:show, text: t("admin.shared.view"), path: root_url(host: tenant.host)) %>
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/admin/tenants_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ def update
private

def tenant_params
params.require(:tenant).permit(:name, :schema)
params.require(:tenant).permit(:name, :schema, :schema_type)
end
end
34 changes: 29 additions & 5 deletions app/models/tenant.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
class Tenant < ApplicationRecord
enum schema_type: %w[subdomain domain]

validates :schema,
presence: true,
uniqueness: true,
Expand All @@ -10,12 +12,26 @@ class Tenant < ApplicationRecord
after_update :rename_schema
after_destroy :destroy_schema

def self.find_by_domain(host)
domain.find_by(schema: host)
end

def self.resolve_host(host)
return nil unless Rails.application.config.multitenancy.present?
return nil if host.blank? || host.match?(Resolv::AddressRegex)

host_domain = allowed_domains.find { |domain| host == domain || host.ends_with?(".#{domain}") }
host.delete_prefix("www.").sub(/\.?#{host_domain}\Z/, "").presence
host_without_www = host.delete_prefix("www.")

if find_by_domain(host)
host
elsif find_by_domain(host_without_www)
host_without_www
else
host_domain = allowed_domains.find { |domain| host == domain || host.ends_with?(".#{domain}") }
schema = host_without_www.sub(/\.?#{host_domain}\Z/, "").presence

schema unless find_by_domain(schema)
end
end

def self.allowed_domains
Expand All @@ -35,6 +51,14 @@ def self.default_host
default_url_options[:host]
end

def self.default_domain
if default_host == "localhost"
"lvh.me"
else
default_host
end
end

def self.current_url_options
default_url_options.merge(host: current_host)
end
Expand All @@ -46,10 +70,10 @@ def self.current_host
def self.host_for(schema)
if schema == "public"
default_host
elsif default_host == "localhost"
"#{schema}.lvh.me"
elsif find_by_domain(schema)
schema
else
"#{schema}.#{default_host}"
"#{schema}.#{default_domain}"
end
end

Expand Down
5 changes: 4 additions & 1 deletion config/locales/en/activerecord.yml
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,10 @@ en:
tag:
name: "Type the name of the topic"
tenant:
schema: "Subdomain"
domain: "Domain"
schema: "Domain / Subdomain"
subdomain: "Subdomain"
url: "URL"
topic:
title: "Title"
description: "Initial text"
Expand Down
3 changes: 3 additions & 0 deletions config/locales/en/admin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1632,6 +1632,9 @@ en:
tenants:
create:
notice: Tenant created successfully
form:
use_subdomain: "Use a subdomain in the %{domain} domain to access this tenant"
use_domain: "Use a different domain to access this tenant"
index:
create: Create tenant
new:
Expand Down
5 changes: 4 additions & 1 deletion config/locales/es/activerecord.yml
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,10 @@ es:
tag:
name: "Escribe el nombre del tema"
tenant:
schema: "Subdominio"
domain: "Dominio"
schema: "Dominio / Subdominio"
subdomain: "Subdominio"
url: "URL"
topic:
title: "Título"
description: "Texto inicial"
Expand Down
3 changes: 3 additions & 0 deletions config/locales/es/admin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,9 @@ es:
tenants:
create:
notice: Entidad creada correctamente
form:
use_subdomain: "Utiliza un subdominio en el dominio %{domain} para acceder a esta entidad"
use_domain: "Utiliza un dominio distinto para acceder a esta entidad"
index:
create: Crear entidad
new:
Expand Down
5 changes: 5 additions & 0 deletions db/migrate/20221120123254_add_schema_type_to_tenants.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddSchemaTypeToTenants < ActiveRecord::Migration[6.0]
def change
add_column :tenants, :schema_type, :integer, null: false, default: 0
end
end
3 changes: 2 additions & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2022_09_15_154808) do
ActiveRecord::Schema.define(version: 2022_11_20_123254) do

# These are extensions that must be enabled in order to support this database
enable_extension "pg_trgm"
Expand Down Expand Up @@ -1561,6 +1561,7 @@
t.string "schema"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "schema_type", default: 0, null: false
t.index ["name"], name: "index_tenants_on_name", unique: true
t.index ["schema"], name: "index_tenants_on_schema", unique: true
end
Expand Down
7 changes: 7 additions & 0 deletions spec/controllers/concerns/tenant_variants_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,11 @@ def index
get :index
expect(response.body).to eq '[:"random-name"]'
end

it "keeps dots in the variant names" do
allow(Tenant).to receive(:current_schema).and_return("random.domain")

get :index
expect(response.body).to eq '[:"random.domain"]'
end
end
4 changes: 4 additions & 0 deletions spec/factories/administration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,9 @@
factory :tenant do
sequence(:name) { |n| "Tenant #{n}" }
sequence(:schema) { |n| "subdomain#{n}" }

trait :domain do
schema_type { :domain }
end
end
end
24 changes: 24 additions & 0 deletions spec/factory_bot/strategy/insert.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module FactoryBot
module Strategy
class Insert
def initialize
@strategy = FactoryBot.strategy_by_name(:attributes_for).new
end

delegate :association, to: :@strategy

def result(evaluation)
build_class = evaluation.instance_variable_get(:@attribute_assigner)
.instance_variable_get(:@build_class)

timestamps = { created_at: Time.current, updated_at: Time.current }.select do |attribute, _|
build_class.has_attribute?(attribute)
end

build_class.insert!(timestamps.merge(@strategy.result(evaluation)))
end
end

FactoryBot.register_strategy(:insert, Insert)
end
end
19 changes: 9 additions & 10 deletions spec/models/abilities/administrator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,17 +183,16 @@
it { should be_able_to :update, Tenant }
it { should_not be_able_to :destroy, Tenant }

it "does not allow administrators from other tenants to manage tenants " do
create(:tenant, schema: "subsidiary")

Tenant.switch("subsidiary") do
admin = create(:administrator).user

expect(admin).not_to be_able_to :create, Tenant
expect(admin).not_to be_able_to :read, Tenant
expect(admin).not_to be_able_to :update, Tenant
expect(admin).not_to be_able_to :destroy, Tenant
context "administrators from other tenants" do
before do
insert(:tenant, schema: "subsidiary")
allow(Tenant).to receive(:current_schema).and_return("subsidiary")
end

it { should_not be_able_to :create, Tenant }
it { should_not be_able_to :read, Tenant }
it { should_not be_able_to :update, Tenant }
it { should_not be_able_to :destroy, Tenant }
end
end
end
Expand Down
7 changes: 3 additions & 4 deletions spec/models/setting_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -193,11 +193,10 @@
end

it "returns the tenant name for other tenants" do
create(:tenant, schema: "new", name: "New Institution")
insert(:tenant, schema: "new", name: "New Institution")
allow(Tenant).to receive(:current_schema).and_return("new")

Tenant.switch("new") do
expect(Setting.default_org_name).to eq "New Institution"
end
expect(Setting.default_org_name).to eq "New Institution"
end
end

Expand Down
Loading