Search code examples
ruby-on-railsdeviseapartment-gem

Apartment switch tenant based on logged user


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.


Solution

  • 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.