Apartment current_tenant resets to 'public' after failed devise login

417 views Asked by At

I use Devise for authentication and Apartment for multi-tenancy support on a SAAS app.

After a failed login, devise "redirects" to the login page (Users::SessionsController#new) and the value of Apartment::Tenant.current which was previously set in a TenantElevator middleware goes back to its default value of "public".

This is happening because Devise isn't actally redirecting to the login page but calling the FailureApp (which renders the login page) with a new rack env and returning its response. The new rack app doesn't have TenantElevator middleware so the tenant isn't set within the rack app.

Does anyone have any idea how to fix this? Maybe a way I can add the TenantElevator middleware to the Failure app?

1

There are 1 answers

0
Favourite Onwuemene On

Just stumbled on this and figured providing an answer may be useful for someone.

Haven't encountered this issue in a while, but looking through the sourcecode of the app I was working on, I fixed this issue by simply modifying where the apartment's middleware is inserted i.e modifying the order of the middleware.

Add the following snippet at the very bottom of your apartment.rb initializer file which should be located at app/config/initializers/apartment.rb

Rails.application.config.middleware.insert_before ActionDispatch::ShowExceptions, Apartment::Elevators::Domain

Essentially, insert your middleware before the ShowExceptions middleware, this ensures Devise, and ShowExceptions middleware, always runs under/within the context of the tenant set by whatever TenantElevator your app uses.

There may currently be a better way to handle this -- I am not sure, but this was the best option I found back when I had this issue.