tenanting 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7c494dc26510302cd4f4697c66378a0c889d8cd7d544acd941e8aa3b8ae46e12
4
- data.tar.gz: 791f00f6e957ff10fe42c98496c2af5b039ab6ebd04d34520b63881c71be6756
3
+ metadata.gz: a53786ca1dbde14a190fb5771d48450892c4febe6995aba62e8679aafe51f6ad
4
+ data.tar.gz: 43aed646d658afacd71cc9c5f027bab6aafe76c72958a5a650368c61c9f238b5
5
5
  SHA512:
6
- metadata.gz: ca16cac52ab1f0661e29c98f4c1629ef4313a9551a16338db83a99c6d82a6722adf47b40ddbd0990fbc71f828d3d04d14b087a3387857ada49090f4d4a95112b
7
- data.tar.gz: 453179c1d8227ed0f8f0843e77c3ed13a2ee88f51345e3d0661f2ed4870eacc99abff983707e7210dbed043df5437ae47d6500e9c46aedb08eaea7b29c0ef372
6
+ metadata.gz: 413d88cea2e9c2aaed3d047dca07b7f2d347f2a850beefaa4bf842d9ada7e9c5330bd16f512d2204469a2cb5607025d1a4a48870551db3764b1fc067254a95b3
7
+ data.tar.gz: 1a92d82269c68fa46976109b01fd2fd4d8ae1750314fbd49553c10f19e071cd7f19bd477a8595b0a145326ad0ffcd426f68e547a0cfdac38865f2469c41639e9
data/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.2.0
6
+
7
+ - Records can be moved to another account inside `AccountScoping.across_accounts`
8
+ - `scoped_to_account` passes other options to the account association, like `counter_cache: true`
9
+ - `--account-from=domain` serves each account from its own subdomain, like `acme.example.com`,
10
+ or a custom domain
11
+ - `--account-from=cookie` keeps the current account in a signed cookie instead of the URL.
12
+ Controllers choose the account with `switch_to_account`
13
+ - Jobs whose account was deleted after they were enqueued raise
14
+ `ActiveJob::DeserializationError`, so `discard_on` and `retry_on` can handle them
15
+
3
16
  ## 0.1.0 (2026-09-21)
4
17
 
5
18
  - Initial release: `bin/rails generate tenanting`
data/README.md CHANGED
@@ -22,6 +22,8 @@ and every query on those tables is scoped to the current account.
22
22
  - [Scoping models](#scoping-models)
23
23
  - [The current account](#the-current-account)
24
24
  - [Controllers and URLs](#controllers-and-urls)
25
+ - [Accounts on subdomains and custom domains](#accounts-on-subdomains-and-custom-domains)
26
+ - [Accounts without URL prefixes](#accounts-without-url-prefixes)
25
27
  - [Background jobs, mailers, and broadcasts](#background-jobs-mailers-and-broadcasts)
26
28
  - [Console, seeds, and data migrations](#console-seeds-and-data-migrations)
27
29
  - [Testing](#testing)
@@ -48,6 +50,15 @@ bin/rails generate tenanting
48
50
  bin/rails db:migrate
49
51
  ```
50
52
 
53
+ By default, account URLs are prefixed with the account ID. Choose where requests find their
54
+ account with `--account-from`:
55
+
56
+ | Option | URLs | |
57
+ | --- | --- | --- |
58
+ | `--account-from=path` (default) | `example.com/123/projects` | [Controllers and URLs](#controllers-and-urls) |
59
+ | `--account-from=domain` | `acme.example.com/projects` or `projects.acme.com/projects` | [Subdomains and custom domains](#accounts-on-subdomains-and-custom-domains) |
60
+ | `--account-from=cookie` | `example.com/projects` | [Without URL prefixes](#accounts-without-url-prefixes) |
61
+
51
62
  Then scope your models to an account:
52
63
 
53
64
  ```ruby
@@ -60,11 +71,11 @@ end
60
71
 
61
72
  | File | What it does |
62
73
  | --- | --- |
63
- | `app/models/account.rb` | The tenant. `#slug` returns its URL prefix, `/123` |
74
+ | `app/models/account.rb` | The tenant. `#slug` returns its URL prefix, `/123`, or `#host` its domain |
64
75
  | `app/models/current.rb` | Adds `attribute :account, :all_accounts` (created if it doesn't exist) |
65
76
  | `app/models/concerns/account_scoping.rb` | `scoped_to_account`, included in `ApplicationRecord` |
66
77
  | `app/controllers/concerns/tenanting.rb` | Sets `Current.account` for each request, included in `ApplicationController` |
67
- | `config/initializers/tenanting.rb` | URL prefix middleware, plus the account for jobs, broadcasts, and the console |
78
+ | `config/initializers/tenanting.rb` | URL prefix middleware or the app's domain, plus the account for jobs, broadcasts, and the console |
68
79
  | `db/migrate/*_create_accounts.rb` | The `accounts` table |
69
80
  | `test/test_helpers/account_test_helper.rb` | `switch_to_account` for tests |
70
81
  | `test/fixtures/accounts.yml` | Two accounts, `one` and `two` |
@@ -75,6 +86,7 @@ When the authentication generator has been run, you also get:
75
86
  | --- | --- |
76
87
  | `app/models/membership.rb` | Joins users to accounts. `User has_many :accounts, through: :memberships` |
77
88
  | `app/controllers/accounts_controller.rb` | An account picker, at `/accounts` |
89
+ | `app/controllers/accounts/switches_controller.rb` | Switches to an account from the picker (cookies only) |
78
90
  | `db/migrate/*_create_memberships.rb` | The `memberships` table, unique on user and account |
79
91
  | `test/fixtures/memberships.yml` | Users `one` and `two` in accounts `one` and `two` |
80
92
 
@@ -102,7 +114,9 @@ class Project < ApplicationRecord
102
114
  end
103
115
  ```
104
116
 
105
- This adds `belongs_to :account` and a default scope on `Current.account`:
117
+ This adds `belongs_to :account` and a default scope on `Current.account`. Other options go to
118
+ that association, like `scoped_to_account counter_cache: true` for an `accounts.projects_count`
119
+ column:
106
120
 
107
121
  ```ruby
108
122
  Current.account = basecamp
@@ -181,7 +195,8 @@ reloading individual records, not just to reads. Scoped models also get three va
181
195
  `params.expect(project: [ :name, :account_id ])`, can't create a record in another account.
182
196
  The same goes for a through model's parent, like a `project_id` from another account.
183
197
  - **The account can't change** once a record is saved, including by moving a through model to a
184
- parent in another account.
198
+ parent in another account. To move records on purpose, see
199
+ [Moving records between accounts](#moving-records-between-accounts).
185
200
  - **`belongs_to` records must be in the same account.** `Task.create!(tag_id: params[:tag_id])`
186
201
  fails when the tag belongs to another account, whether it's assigned by ID or as a record.
187
202
 
@@ -233,6 +248,20 @@ end
233
248
  model, such as a soft-delete scope, still apply. Both are easy to search for when reviewing code
234
249
  that crosses accounts.
235
250
 
251
+ ### Moving records between accounts
252
+
253
+ Records can't change their account, except inside `across_accounts`, which is how a transfer
254
+ says it means to:
255
+
256
+ ```ruby
257
+ AccountScoping.across_accounts do
258
+ project.update!(account: other_account)
259
+ end
260
+ ```
261
+
262
+ Through models move with their parent, or by moving to a parent in another account. Records the
263
+ moved record `belongs_to` must be in its new account, so move them together.
264
+
236
265
  ## Controllers and URLs
237
266
 
238
267
  ### Account URLs
@@ -280,7 +309,144 @@ without an account prefix redirects to the account picker, which goes straight i
280
309
  when the user only has one.
281
310
 
282
311
  Without authentication, any account ID in the URL is accepted, and requests without one return
283
- 404. Add your own authorization in `find_account_by_slug`.
312
+ 404. Add your own authorization in `find_account`.
313
+
314
+ ## Accounts on subdomains and custom domains
315
+
316
+ Generate with `--account-from=domain` to serve each account from its own subdomain, and
317
+ optionally from a custom domain:
318
+
319
+ ```sh
320
+ bin/rails generate tenanting --account-from=domain
321
+ ```
322
+
323
+ Accounts get a unique `subdomain`, which defaults to their name, and an optional, unique
324
+ `domain`:
325
+
326
+ ```ruby
327
+ Account.create!(name: "Acme") # acme.example.com
328
+ Account.create!(name: "Initech", domain: "tps.initech.com") # tps.initech.com
329
+ ```
330
+
331
+ The generator sets the app's domain in each environment. Change it to your domain in
332
+ `config/environments/production.rb`:
333
+
334
+ ```ruby
335
+ config.x.account_domain = "example.com"
336
+ ```
337
+
338
+ In development, it's `localhost`. Browsers resolve every subdomain of `localhost`, so accounts
339
+ are at `acme.localhost:3000` without any DNS setup, and Rails allows those hosts by default.
340
+
341
+ The `Tenanting` concern finds the account with `Account.find_by_host(request.host)`. A subdomain
342
+ of the app's domain is looked up by `subdomain`, and any other host by `domain`. `Account#host`
343
+ returns the custom domain if there is one, and the subdomain otherwise. Use it to link into an
344
+ account:
345
+
346
+ ```erb
347
+ <%= link_to account.name, root_url(host: account.host) %>
348
+ ```
349
+
350
+ Routes and URL helpers don't change, and paths like `project_path(@project)` stay on the current
351
+ host. Emails link to the host of the account they were sent from.
352
+
353
+ With authentication, the app's domain and `www` show the account picker, which links to each
354
+ account's host. A host for an account the user isn't a member of, or for no account at all,
355
+ returns 404 Not Found.
356
+
357
+ Subdomains are validated as DNS labels, and `www`, `app`, `admin`, `api`, `assets`, and `mail` are
358
+ reserved. Edit `Account::RESERVED_SUBDOMAINS` to reserve others, like any subdomains your app
359
+ uses itself. Custom domains can't be on the app's domain, so an account can't take over another
360
+ account's subdomain.
361
+
362
+ ### Signing in
363
+
364
+ Cookies belong to the host that set them, so users sign in separately on each account's host,
365
+ whichever authentication library you use. Custom domains always work this way, because browsers
366
+ never share cookies between different domains.
367
+
368
+ To share one sign-in across subdomains, set the cookie domain to your app's domain, like
369
+ `domain: ".example.com"`, in your authentication library: on the session cookie with the Rails
370
+ authentication generator, the session store with Devise, or `config.cookie_domain` with
371
+ Clearance. Avoid `domain: :all`, which on a custom domain covers that domain's parent instead.
372
+ Users still sign in separately on custom domains.
373
+
374
+ Session cookies aren't tied to a host, though. An account that controls its custom domain's DNS
375
+ could collect the session cookies of members who sign in there and use them on the app's domain,
376
+ including in other accounts those members belong to. If that matters for your app, store the host
377
+ on each session and only accept it on that host, or require members to sign in on the app's
378
+ domain.
379
+
380
+ ### Custom domains
381
+
382
+ Tenanting finds accounts by custom domain, but pointing a domain at your app is up to you. Each
383
+ custom domain needs DNS that points at your app, a TLS certificate, and, if you've set
384
+ `config.hosts`, to be allowed there. Consider verifying that an account owns a domain before
385
+ saving it.
386
+
387
+ ### Testing
388
+
389
+ In integration tests, `switch_to_account` sends requests to the account's host. Sign ins belong
390
+ to a host, just like in a browser, so switch accounts before signing in:
391
+
392
+ ```ruby
393
+ setup do
394
+ switch_to_account accounts(:one)
395
+ sign_in_as users(:one)
396
+ end
397
+
398
+ test "index" do
399
+ get projects_url # GET http://one.example.com/projects
400
+ assert_response :success
401
+ end
402
+ ```
403
+
404
+ Fixtures need a subdomain for each account. The domain is `example.com` in tests, so
405
+ `accounts(:one)` is at `one.example.com`.
406
+
407
+ ## Accounts without URL prefixes
408
+
409
+ Some apps don't want the account in the URL. Generate with `--account-from=cookie` to keep the
410
+ current account in a signed cookie instead:
411
+
412
+ ```sh
413
+ bin/rails generate tenanting --account-from=cookie
414
+ ```
415
+
416
+ URLs stay as they are, like `/projects/1`, and the `Tenanting` concern reads the account from the
417
+ cookie instead of the URL. To choose an account, call `switch_to_account` in a controller. It
418
+ sets `Current.account` for the current request and saves it in the cookie for later ones:
419
+
420
+ ```ruby
421
+ class Accounts::SwitchesController < ApplicationController
422
+ allow_accountless_access
423
+
424
+ def create
425
+ switch_to_account Current.user.accounts.find(params[:account_id])
426
+ redirect_to root_url
427
+ end
428
+ end
429
+ ```
430
+
431
+ With authentication, that controller is generated for you. The account picker at `/accounts`
432
+ posts to it, so it's the only place that changes the account, even when the user only has one. The cookie is checked against
433
+ `Current.user.accounts` on every request. If the account in it isn't one of the user's, like after
434
+ another user signs in on the same browser, the request is sent to the picker instead.
435
+
436
+ Without authentication, requests without an account return 404 Not Found. Call
437
+ `switch_to_account` wherever your app decides which account someone is in, and add your own
438
+ authorization in `find_account`.
439
+
440
+ Compared to path prefixes:
441
+
442
+ - **One account per browser.** Every tab uses the account that was chosen last, and switching
443
+ accounts in one tab switches the others on their next request.
444
+ - **Links don't include the account.** A link to `/projects/1` sent to someone opens in their
445
+ current account. For a record in another account, it returns 404 until they switch accounts.
446
+ - **Mailers and broadcasts don't add an account prefix.** Jobs, including `deliver_later` and
447
+ `broadcast_*_later`, still run in the account they were enqueued from.
448
+ - **Integration tests set the cookie.** `switch_to_account` sets the signed cookie, the same way
449
+ `sign_in_as` sets the session cookie, so requests find the account just like in production.
284
450
 
285
451
  ## Background jobs, mailers, and broadcasts
286
452
 
@@ -299,6 +465,17 @@ The account is serialized as a GlobalID in the job's `current_account` key. Argu
299
465
  deserialized inside the account, so scoped records can be passed as arguments. A job enqueued
300
466
  without an account raises `MissingAccountError` as soon as it queries a scoped model.
301
467
 
468
+ If the account is deleted before the job runs, the job raises `ActiveJob::DeserializationError`,
469
+ the same as when a record passed as an argument has been deleted. Unless it's handled, your queue
470
+ backend retries it and then marks it as failed. To drop these jobs instead, discard them in
471
+ `ApplicationJob`:
472
+
473
+ ```ruby
474
+ class ApplicationJob < ActiveJob::Base
475
+ discard_on ActiveJob::DeserializationError
476
+ end
477
+ ```
478
+
302
479
  ### Mailers
303
480
 
304
481
  `ApplicationMailer#default_url_options` adds the account prefix, so links in emails point into
@@ -365,8 +542,8 @@ after each request, because Rails resets `Current` around requests:
365
542
  ```ruby
366
543
  class ProjectsControllerTest < ActionDispatch::IntegrationTest
367
544
  setup do
368
- sign_in_as users(:one)
369
545
  switch_to_account accounts(:one)
546
+ sign_in_as users(:one)
370
547
  end
371
548
 
372
549
  test "create" do
@@ -387,25 +564,11 @@ end
387
564
 
388
565
  The generated code is yours to change. Some common changes:
389
566
 
390
- ### Subdomains or custom domains instead of a path prefix
391
-
392
- Remove the `AccountSlug` middleware from `config/initializers/tenanting.rb`, add a column to
393
- accounts, and look the account up from the request in the `Tenanting` concern:
394
-
395
- ```ruby
396
- def find_account_by_slug
397
- Current.user&.accounts&.find_by(subdomain: request.subdomain)
398
- end
399
- ```
400
-
401
- Also change `Account#slug`, which is used as the URL prefix in mailers, broadcasts, and tests.
402
- Instead, set the `host` in those places, or set `subdomain:` in your URL helpers.
403
-
404
567
  ### Public IDs instead of database IDs
405
568
 
406
569
  `AccountSlug::PATTERN` matches a numeric first path segment. To keep database IDs out of URLs,
407
570
  store a random public ID on each account, change the pattern to match it, look it up by that
408
- column in `find_account_by_slug`, and return it from `Account#slug`.
571
+ column in `find_account`, and return it from `Account#slug`.
409
572
 
410
573
  Because any numeric first segment is treated as an account, avoid top-level routes whose path
411
574
  starts with a number, or use a longer format (Fizzy pads IDs to at least 7 digits).
@@ -450,8 +613,8 @@ It does not cover:
450
613
  | `ActsAsTenant.current_tenant = account` | `Current.account = account` |
451
614
  | `ActsAsTenant.with_tenant(account) { }` | `Current.set(account: account) { }` |
452
615
  | `ActsAsTenant.without_tenant { }` | `AccountScoping.across_accounts { }` |
453
- | `set_current_tenant_by_subdomain` | Path prefixes, or see [Subdomains](#subdomains-or-custom-domains-instead-of-a-path-prefix) |
454
- | `set_current_tenant_through_filter` | Edit `find_account_by_slug` |
616
+ | `set_current_tenant_by_subdomain` | `--account-from=domain` |
617
+ | `set_current_tenant_through_filter` | `--account-from=cookie` and `switch_to_account`, or edit `find_account` |
455
618
  | `config.require_tenant = true` | Always on |
456
619
  | `validates_uniqueness_to_tenant :name` | `validates :name, uniqueness: { scope: :account_id }` |
457
620
  | `ActsAsTenant::ActiveJobExtensions` | Built in, for every Active Job |
@@ -469,7 +632,7 @@ To migrate:
469
632
  Reach them through an association instead, like `Current.account.users`.
470
633
  3. Replace `ActsAsTenant` calls using the table above.
471
634
  4. Remove your `set_current_tenant_*` calls. `Tenanting` sets `Current.account` from the URL, or
472
- from wherever you change `find_account_by_slug` to look.
635
+ from wherever you change `find_account` to look.
473
636
  5. Wrap code that ran without a tenant in `Current.set` or `across_accounts`. Your test suite will
474
637
  point these out by raising `AccountScoping::MissingAccountError`.
475
638
  6. Remove the `acts_as_tenant` gem.
@@ -482,8 +645,10 @@ bundle exec rake test # Generator tests
482
645
  bundle exec rake test:integration # Generates a Rails app and runs its tests
483
646
  ```
484
647
 
485
- The integration task creates a new Rails app, runs the authentication and tenanting generators,
486
- adds the models and tests in `test/integration/app`, and runs the app's test suite.
648
+ The integration task creates a new Rails app for each of `--account-from=path`,
649
+ `--account-from=domain`, and `--account-from=cookie`, runs the authentication and tenanting generators, adds the models and
650
+ tests from `test/integration/app` and `test/integration/<mode>`, and runs the app's test suite.
651
+ Run one mode with `bin/integration domain`.
487
652
 
488
653
  ## License
489
654
 
@@ -7,11 +7,19 @@ Description:
7
7
  Run the authentication generator first to also get memberships between users
8
8
  and accounts, and an account picker.
9
9
 
10
+ Accounts come from a URL prefix by default. Pass --account-from=domain to serve
11
+ each account from its own subdomain (acme.example.com) or custom domain, or
12
+ --account-from=cookie to keep the current account in a signed cookie, where
13
+ controllers choose it with switch_to_account(account).
14
+
10
15
  Example:
11
16
  bin/rails generate authentication
12
17
  bin/rails generate tenanting
13
18
  bin/rails db:migrate
14
19
 
20
+ bin/rails generate tenanting --account-from=domain
21
+ bin/rails generate tenanting --account-from=cookie
22
+
15
23
  Then scope models to an account:
16
24
 
17
25
  class Project < ApplicationRecord
@@ -0,0 +1,8 @@
1
+ class Accounts::SwitchesController < ApplicationController
2
+ allow_accountless_access
3
+
4
+ def create
5
+ switch_to_account Current.user.accounts.find(params[:account_id])
6
+ redirect_to root_url
7
+ end
8
+ end
@@ -3,6 +3,10 @@ class AccountsController < ApplicationController
3
3
 
4
4
  def index
5
5
  @accounts = Current.user.accounts.order(:name)
6
+ <% if path_prefix? -%>
6
7
  redirect_to root_url(script_name: @accounts.first.slug) if @accounts.one?
8
+ <% elsif domain? -%>
9
+ redirect_to root_url(host: @accounts.first.host), allow_other_host: true if @accounts.one?
10
+ <% end -%>
7
11
  end
8
12
  end
@@ -17,28 +17,52 @@ module Tenanting
17
17
  end
18
18
 
19
19
  def resume_account
20
- Current.account ||= find_account_by_slug
20
+ Current.account ||= find_account
21
21
  end
22
22
 
23
- def find_account_by_slug
24
- if account_id = request.env["account_slug.id"]
23
+ def find_account
24
+ <% if domain? -%>
25
+ <% if authentication? -%>
26
+ Current.user&.accounts&.find_by_host(request.host)
27
+ <% else -%>
28
+ Account.find_by_host(request.host)
29
+ <% end -%>
30
+ <% else -%>
31
+ if account_id = <%= path_prefix? ? 'request.env["account_slug.id"]' : "cookies.signed[:account_id]" %>
25
32
  <% if authentication? -%>
26
33
  Current.user&.accounts&.find_by(id: account_id)
27
34
  <% else -%>
28
35
  Account.find_by(id: account_id)
29
36
  <% end -%>
30
37
  end
38
+ <% end -%>
31
39
  end
32
40
 
33
41
  def request_account
34
- <% if authentication? -%>
42
+ <% if !authentication? -%>
43
+ head :not_found
44
+ <% elsif path_prefix? -%>
35
45
  if request.env["account_slug.id"]
36
46
  head :not_found
37
47
  else
38
48
  redirect_to accounts_url(script_name: "")
39
49
  end
50
+ <% elsif domain? -%>
51
+ if AccountDomain.root_host?(request.host)
52
+ redirect_to accounts_url
53
+ else
54
+ head :not_found
55
+ end
40
56
  <% else -%>
41
- head :not_found
57
+ redirect_to accounts_url
42
58
  <% end -%>
43
59
  end
60
+ <% if cookie? -%>
61
+
62
+ # Sets the account for this request and the ones after it, e.g. from an account picker.
63
+ def switch_to_account(account)
64
+ cookies.signed.permanent[:account_id] = { value: account.id, httponly: true, same_site: :lax }
65
+ Current.account = account
66
+ end
67
+ <% end -%>
44
68
  end
@@ -1,14 +1,55 @@
1
1
  class Account < ApplicationRecord
2
+ <% if domain? -%>
3
+ RESERVED_SUBDOMAINS = %w[ www app admin api assets mail ]
4
+ LABEL = /[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/ # One part of a domain name
5
+
6
+ <% end -%>
2
7
  <% if authentication? -%>
3
8
  has_many :memberships, dependent: :destroy
4
9
  has_many :users, through: :memberships
5
10
 
6
11
  <% end -%>
7
12
  validates :name, presence: true
13
+ <% if domain? -%>
14
+ validates :subdomain, presence: true, uniqueness: true, exclusion: { in: RESERVED_SUBDOMAINS },
15
+ format: { with: /\A#{LABEL}\z/, message: "can only contain letters, numbers, and dashes" }
16
+ validates :domain, uniqueness: true, allow_nil: true,
17
+ format: { with: /\A(?:#{LABEL}\.)+[a-z]{2,}\z/, message: "isn't a valid domain" }
18
+ validate :domain_is_custom
19
+
20
+ normalizes :subdomain, with: ->(subdomain) { subdomain.strip.downcase }
21
+ normalizes :domain, with: ->(domain) { domain.strip.downcase.delete_suffix(".").presence }
22
+
23
+ before_validation { self.subdomain = name&.parameterize if subdomain.blank? }
24
+
25
+ # The account served from a host: a subdomain of the app's domain, or a custom domain.
26
+ def self.find_by_host(host)
27
+ if subdomain = AccountDomain.subdomain_of(host)
28
+ find_by(subdomain: subdomain)
29
+ else
30
+ find_by(domain: host)
31
+ end
32
+ end
33
+
34
+ # The host for this account's URLs. Pass it as the host to link into an account from outside
35
+ # of it, e.g. root_url(host: account.host).
36
+ def host
37
+ domain || "#{subdomain}.#{AccountDomain.domain}"
38
+ end
39
+
40
+ private
41
+ def domain_is_custom
42
+ if domain == AccountDomain.domain || domain&.end_with?(".#{AccountDomain.domain}")
43
+ errors.add(:domain, "must be your own domain. Use the subdomain for #{AccountDomain.domain} addresses")
44
+ end
45
+ end
46
+ <% end -%>
47
+ <% if path_prefix? -%>
8
48
 
9
49
  # The path prefix for this account's URLs. Pass it as the script_name to link into an
10
50
  # account from outside of it, e.g. root_url(script_name: account.slug).
11
51
  def slug
12
52
  "/#{id}"
13
53
  end
54
+ <% end -%>
14
55
  end
@@ -54,9 +54,11 @@ module AccountScoping
54
54
  # [through] A belongs_to association to a scoped model, for tables without an account_id column.
55
55
  # [optional] Allows records without an account. They can be created and queried outside of any
56
56
  # account, but are hidden from, and can't be created in, an account.
57
- def scoped_to_account(through: nil, optional: false)
58
- if through && optional
59
- raise ArgumentError, "optional: is for models with an account_id column. Make the #{through} association optional instead."
57
+ #
58
+ # Other options go to the account association, e.g. scoped_to_account counter_cache: true.
59
+ def scoped_to_account(through: nil, optional: false, **options)
60
+ if through && (option = optional ? :optional : options.keys.first)
61
+ raise ArgumentError, "#{option}: is for models with an account_id column. Pass it to the #{through} association instead."
60
62
  end
61
63
 
62
64
  self.account_scoping = { through: through, optional: optional }.freeze
@@ -64,13 +66,13 @@ module AccountScoping
64
66
  if through
65
67
  delegate :account, :account_id, to: through, allow_nil: true
66
68
  else
67
- belongs_to :account, optional: optional, default: -> { Current.account }
69
+ belongs_to :account, optional: optional, default: -> { Current.account }, **options
68
70
  end
69
71
 
70
72
  default_scope(all_queries: true) { AccountScoping.scope_to_current_account(self) }
71
73
 
72
74
  validate :account_is_current, if: -> { Current.account && !Current.all_accounts }
73
- validate :account_is_unchanged, on: :update
75
+ validate :account_is_unchanged, on: :update, unless: -> { Current.all_accounts }
74
76
  validate :associations_belong_to_same_account
75
77
  end
76
78
 
@@ -95,6 +97,7 @@ module AccountScoping
95
97
  end
96
98
  end
97
99
 
100
+ # Records stay in their account, except across_accounts, for moving them between accounts on purpose.
98
101
  def account_is_unchanged
99
102
  if changing_account? && account_id != account_id_in_database_for_scoping
100
103
  errors.add(account_scoping_association.name, account_scoping[:through] ? "must belong to the same account" : "can't be changed")
@@ -2,6 +2,12 @@
2
2
 
3
3
  <ul>
4
4
  <%% @accounts.each do |account| %>
5
+ <% if path_prefix? -%>
5
6
  <li><%%= link_to account.name, root_url(script_name: account.slug) %></li>
7
+ <% elsif domain? -%>
8
+ <li><%%= link_to account.name, root_url(host: account.host) %></li>
9
+ <% else -%>
10
+ <li><%%= button_to account.name, account_switch_path(account) %></li>
11
+ <% end -%>
6
12
  <%% end %>
7
13
  </ul>
@@ -1,3 +1,4 @@
1
+ <% if path_prefix? -%>
1
2
  # Account URLs are prefixed with the account ID: /123/projects/1
2
3
  #
3
4
  # The middleware moves that prefix from PATH_INFO into SCRIPT_NAME, the same way a mounted
@@ -27,6 +28,30 @@ end
27
28
 
28
29
  Rails.application.config.middleware.use AccountSlug::Extractor
29
30
 
31
+ <% elsif domain? -%>
32
+ # Accounts are served from subdomains of the app's domain, like acme.example.com, or from their
33
+ # own custom domain, like projects.acme.com. Set the domain with config.x.account_domain in
34
+ # config/environments.
35
+ module AccountDomain
36
+ def self.domain
37
+ Rails.configuration.x.account_domain
38
+ end
39
+
40
+ # "acme" for acme.example.com. nil for the app's domain itself, deeper subdomains, and custom domains.
41
+ def self.subdomain_of(host)
42
+ if host.end_with?(".#{domain}")
43
+ subdomain = host.delete_suffix(".#{domain}")
44
+ subdomain unless subdomain.include?(".")
45
+ end
46
+ end
47
+
48
+ # Whether the host serves pages outside of any account, like the sign in page and account picker.
49
+ def self.root_host?(host)
50
+ host == domain || host == "www.#{domain}"
51
+ end
52
+ end
53
+
54
+ <% end -%>
30
55
  # Jobs run in the account they were enqueued from. This covers every Active Job,
31
56
  # including deliver_later, not just jobs that inherit from ApplicationJob.
32
57
  module AccountScopedJob
@@ -38,21 +63,35 @@ module AccountScopedJob
38
63
  end
39
64
 
40
65
  def serialize
41
- super.merge("current_account" => current_account&.to_global_id&.to_s)
66
+ super.merge("current_account" => current_account&.to_global_id&.to_s || @serialized_current_account)
42
67
  end
43
68
 
44
69
  def deserialize(job_data)
45
70
  super
46
- @current_account = GlobalID::Locator.locate(job_data["current_account"]) if job_data["current_account"]
71
+ @serialized_current_account = job_data["current_account"]
47
72
  end
48
73
 
49
74
  def perform_now
50
- if current_account
51
- Current.set(account: current_account) { super }
52
- else
75
+ Current.set(account: current_account || Current.account) { super }
76
+ end
77
+
78
+ private
79
+ # The account is located with the arguments, inside perform_now's rescue. If it was deleted
80
+ # after the job was enqueued, the job raises ActiveJob::DeserializationError, which
81
+ # discard_on and retry_on can handle, like a deleted record passed as an argument.
82
+ def deserialize_arguments_if_needed
83
+ if @serialized_current_account && !current_account
84
+ Current.account = @current_account = locate_current_account
85
+ end
86
+
53
87
  super
54
88
  end
55
- end
89
+
90
+ def locate_current_account
91
+ GlobalID::Locator.locate(@serialized_current_account)
92
+ rescue ActiveRecord::RecordNotFound
93
+ raise ActiveJob::DeserializationError
94
+ end
56
95
  end
57
96
 
58
97
  ActiveSupport.on_load(:active_job) { prepend AccountScopedJob }
@@ -72,7 +111,7 @@ Rails.application.console do
72
111
  end
73
112
  }
74
113
  end
75
- <% if turbo? -%>
114
+ <% if path_prefix? && turbo? -%>
76
115
 
77
116
  # Turbo Stream broadcasts render outside of a request, so render them with the account
78
117
  # prefix to keep links in broadcast partials pointing into the account.
@@ -2,6 +2,10 @@ class CreateAccounts < ActiveRecord::Migration<%= migration_version %>
2
2
  def change
3
3
  create_table :accounts do |t|
4
4
  t.string :name, null: false
5
+ <% if domain? -%>
6
+ t.string :subdomain, null: false, index: { unique: true }
7
+ t.string :domain, index: { unique: true }
8
+ <% end -%>
5
9
 
6
10
  t.timestamps
7
11
  end
@@ -1,5 +1,11 @@
1
1
  one:
2
2
  name: Account One
3
+ <% if domain? -%>
4
+ subdomain: one
5
+ <% end -%>
3
6
 
4
7
  two:
5
8
  name: Account Two
9
+ <% if domain? -%>
10
+ subdomain: two
11
+ <% end -%>
@@ -5,11 +5,32 @@ module AccountTestHelper
5
5
  end
6
6
 
7
7
  module AccountIntegrationTestHelper
8
+ <% if path_prefix? -%>
8
9
  # Also prefixes generated URLs with the account, so requests resolve it from the path.
10
+ <% elsif domain? -%>
11
+ # Also sends requests to the account's host, so requests resolve it from the domain. Sign in
12
+ # after switching, since sign ins belong to a host, like in a browser.
13
+ <% else -%>
14
+ # Also sets the account cookie, so requests resolve it the same way as in production.
15
+ <% end -%>
9
16
  def switch_to_account(account)
10
17
  super
11
18
  @switched_account = account
19
+ <% if path_prefix? -%>
12
20
  self.default_url_options = default_url_options.merge(script_name: account&.slug)
21
+ <% elsif domain? -%>
22
+ host! account ? account.host : "www.#{AccountDomain.domain}"
23
+ <% else -%>
24
+
25
+ if account
26
+ ActionDispatch::TestRequest.create.cookie_jar.tap do |cookie_jar|
27
+ cookie_jar.signed[:account_id] = account.id
28
+ cookies[:account_id] = cookie_jar[:account_id]
29
+ end
30
+ else
31
+ cookies.delete(:account_id)
32
+ end
33
+ <% end -%>
13
34
  end
14
35
 
15
36
  # Rails resets Current around each request, so restore the account for assertions afterwards.
@@ -11,6 +11,10 @@ class TenantingGenerator < Rails::Generators::Base
11
11
 
12
12
  source_root File.expand_path("templates", __dir__)
13
13
 
14
+ class_option :account_from, type: :string, default: "path", enum: %w[ path domain cookie ],
15
+ desc: "Where requests find their account: a URL path prefix (/123/projects), the domain " \
16
+ "(acme.example.com or a custom domain), or a signed cookie"
17
+
14
18
  def create_tenanting_files
15
19
  template "app/models/account.rb"
16
20
  template "app/models/concerns/account_scoping.rb"
@@ -20,6 +24,7 @@ class TenantingGenerator < Rails::Generators::Base
20
24
  if authentication?
21
25
  template "app/models/membership.rb"
22
26
  template "app/controllers/accounts_controller.rb"
27
+ template "app/controllers/accounts/switches_controller.rb" if cookie?
23
28
  template "app/views/accounts/index.html.erb"
24
29
  end
25
30
  end
@@ -32,6 +37,18 @@ class TenantingGenerator < Rails::Generators::Base
32
37
  end
33
38
  end
34
39
 
40
+ def configure_account_domain
41
+ if domain?
42
+ { development: "localhost", test: "example.com", production: "example.com" }.each do |env, domain|
43
+ environment <<~RUBY, env: env
44
+ # Accounts are served from subdomains of this domain, like acme.#{domain}, and from custom domains.
45
+ config.x.account_domain = "#{domain}"
46
+
47
+ RUBY
48
+ end
49
+ end
50
+ end
51
+
35
52
  def configure_application_record
36
53
  if read("app/models/application_record.rb").include?(" primary_abstract_class\n")
37
54
  inject_into_file "app/models/application_record.rb", "\n include AccountScoping\n", after: " primary_abstract_class\n"
@@ -64,19 +81,29 @@ class TenantingGenerator < Rails::Generators::Base
64
81
  end
65
82
 
66
83
  def configure_mailers
67
- if exist?("app/mailers/application_mailer.rb")
68
- inject_into_class "app/mailers/application_mailer.rb", "ApplicationMailer", <<~RUBY.indent(2)
69
- # Links in emails point into the account they were sent from, including with deliver_later.
70
- def default_url_options
71
- super.merge(script_name: Current.account&.slug)
72
- end
84
+ return if cookie? || !exist?("app/mailers/application_mailer.rb")
73
85
 
74
- RUBY
75
- end
86
+ inject_into_class "app/mailers/application_mailer.rb", "ApplicationMailer", <<~RUBY.indent(2)
87
+ # Links in emails point into the account they were sent from, including with deliver_later.
88
+ def default_url_options
89
+ #{path_prefix? ? "super.merge(script_name: Current.account&.slug)" : "Current.account ? super.merge(host: Current.account.host) : super"}
90
+ end
91
+
92
+ RUBY
76
93
  end
77
94
 
78
95
  def configure_routes
79
- route "resources :accounts, only: :index" if authentication?
96
+ if authentication?
97
+ if cookie?
98
+ route <<~RUBY.chomp
99
+ resources :accounts, only: :index do
100
+ resource :switch, only: :create, module: :accounts
101
+ end
102
+ RUBY
103
+ else
104
+ route "resources :accounts, only: :index"
105
+ end
106
+ end
80
107
  end
81
108
 
82
109
  def add_migrations
@@ -98,6 +125,18 @@ class TenantingGenerator < Rails::Generators::Base
98
125
  exist?("app/controllers/concerns/authentication.rb") && exist?("app/models/user.rb")
99
126
  end
100
127
 
128
+ def path_prefix?
129
+ options[:account_from] == "path"
130
+ end
131
+
132
+ def domain?
133
+ options[:account_from] == "domain"
134
+ end
135
+
136
+ def cookie?
137
+ options[:account_from] == "cookie"
138
+ end
139
+
101
140
  def turbo?
102
141
  exist?("Gemfile") && read("Gemfile").match?(/^\s*gem ["']turbo-rails["']/)
103
142
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tenanting
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Chris Oliver
@@ -50,6 +50,7 @@ files:
50
50
  - MIT-LICENSE
51
51
  - README.md
52
52
  - lib/generators/tenanting/USAGE
53
+ - lib/generators/tenanting/templates/app/controllers/accounts/switches_controller.rb.tt
53
54
  - lib/generators/tenanting/templates/app/controllers/accounts_controller.rb.tt
54
55
  - lib/generators/tenanting/templates/app/controllers/concerns/tenanting.rb.tt
55
56
  - lib/generators/tenanting/templates/app/models/account.rb.tt
@@ -86,7 +87,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
86
87
  - !ruby/object:Gem::Version
87
88
  version: '0'
88
89
  requirements: []
89
- rubygems_version: 4.0.21
90
+ rubygems_version: 4.0.20
90
91
  specification_version: 4
91
92
  summary: A multitenancy generator for Rails, in the style of the authentication generator
92
93
  test_files: []