Use the right tenant after Devise redirections

This is something we had read about a long time ago, but didn't find how
to reproduce the issue until now.

As mentioned in the Apartment documentation:

> it's important to consider that you may want to maintain the
> "selected" tenant through different parts of the Rack application
> stack. For example, the Devise gem adds the Warden::Manager middleware
> at the end of the stack in the examples above, our
> Apartment::Elevators::Subdomain middleware would come after it.
> Trouble is, Apartment resets the selected tenant after the request is
> finished, so some redirects (e.g.  authentication) in Devise will be
> run in the context of the "public" tenant. The same issue would also
> effect a gem such as the better_errors gem which inserts a middleware
> quite early in the Rails middleware stack.
>
> To resolve this issue, consider adding the Apartment middleware at a
> location in the Rack stack that makes sense for your needs, e.g.:
>
> Rails.application.config.middleware.insert_before Warden::Manager,
> Apartment::Elevators::Subdomain
>
> Now work done in the Warden middleware is wrapped in the
> Apartment::Tenant.switch context started in the Generic elevator.
This commit is contained in:
Javi Martín
2022-11-02 23:24:35 +01:00
parent 384057cb48
commit e38b860374
2 changed files with 14 additions and 1 deletions

View File

@@ -107,7 +107,7 @@ end
# Setup a custom Tenant switching middleware. The Proc should return the name of the Tenant that
# you want to switch to.
Rails.application.config.middleware.use Apartment::Elevators::Generic, ->(request) do
Rails.application.config.middleware.insert_before Warden::Manager, Apartment::Elevators::Generic, ->(request) do
Tenant.resolve_host(request.host)
end