5

I'm trying to implement a custom elevator for apartment based on user login on a per request basis.

Basically what I'm trying to achieve is:

  • Every time a request comes in, switch to the correct tenant
  • If there's no logged user, the default tenant is select

However, my problem is that I don't how to retrieve the current user from the request(Rack::Request) object provided by the Generic Elevator. Any tips on how to do it or there's any other way to get the current user without the request?

I'm using devise for authentication.

Nuno
  • 515
  • 1
  • 5
  • 21
  • So if a request comes in from a user that is not logged in you want to switch to a default tenant? – Nathan Sep 02 '15 at 12:20
  • Yes, and if a request comes in and a user is logged in, I want to switch to a tentant based on the user – Nuno Sep 02 '15 at 13:30
  • I'm confused about your problem. I'm under the impression that the gem already does this. In fact that's the whole point of the gem. – Nathan Sep 02 '15 at 19:18
  • @Nathan by default the gem switches tenants by subdomain using what they call elevators. Apart from that they also have elevators to change tenants by domain or full host... However if you want something different you need to build your custom elevator and that what I did. – Nuno Sep 02 '15 at 22:21

1 Answers1

6

For those with the same problem as me this was my solution.

config/initializers/apartment.rb

#My excluded models    
config.excluded_models = %w{ User }

Rails.application.config.middleware.use 'Apartment::Elevators::Generic', lambda { |request|
      tenant_name = nil
  


  if request.env['rack.session']['warden.user.user.key'] != nil
      tenant_name = User.find(request.env['rack.session']['warden.user.user.key'][0][0]).account.name
  end

  return tenant_name
}

However I'm not sure that this is 100% failproof so I will post updates if I find something wrong with it.

Community
  • 1
  • 1
Nuno
  • 515
  • 1
  • 5
  • 21
  • If you are using devise gem for authentication (which i am guessing you are since you are using warden), an alternative is to run Apartment::Tenant.switch! by overriding Devise's sessions controller. – muhammadn Mar 19 '16 at 14:52
  • I had to remove the quotes around `Apartment::Elevators::Generic` to make it work. I am on Rails 6.1. – Angelo Igitego May 01 '23 at 20:18