-->

Switching Apartment tenants in Active Admin

2019-08-15 12:48发布

问题:

This is an extension of my previous post:

Active Admin and the Apartment Gem

I thought I had this working but I am stuck. I have a Company model in the public schema as the tenant model and Locations in individual tenants. Here is my Active Admin location.rb file:

ActiveAdmin.register Location do

#Apartment::Tenant.switch!('abc')

controller do

  #Apartment::Tenant.switch!('abc')

  before_filter do

    Apartment::Tenant.switch!('abc')

    skip_authorization
    skip_policy_scope

  end

end

end

The skip_authorization skip_policy_scope are from some Pundit issues I still have with AA. As you can see I tried adding the Apartment::Tenant.switch in a few places. Inside the controller block is the only place I can get it to work.

When I load the Locations index page it works fine and I see my tenant locations. The issue is that if I go back to the Dashboard or an other page and go back to Locations and call Apartment::Tenant.switch I get kicked back to the AA login screen and I can't log back in. I have to manually enter the AA logout path to force an logout.

It's very weird and not sure how else to trouble shoot this. The logs don't show much.

I was going to ad some logic here with a menu drop down to set a session variable etc. and then have the resource pages call Apartment::Tenant.switch when required but this is a show stopper as of now. No idea if it's Devise, Pundit, Apartment, Active Admin or a combination.

UPDATE

Some progress - tried to add the output of the switch! call to a logger debug and that 'solved' the issue. If I set the switch call to a variable it also goes away:

logger.debug "Apartment Switch: #{Apartment::Tenant.switch!('abc').inspect}"    
new_tenant = Apartment::Tenant.switch!('abc')

UPDATE 2

My previous update was erroneous - the issue remains. I have narrowed it down to Devise. The second switch! call never gets called as Devise throws a 401 error and kicks you out first. I disabled Devise for Active Admin and my switching system works fine. I can use a simple Company dropdown and sessions to switch the tenants on the fly. Devise somehow does not like this at all.

Here is a Gist of my AA files: https://gist.github.com/jasper502/8fd16c31ee26667c5a16

回答1:

I might be a little late, but have you tried storing the current tenant before switching to 'abc' on the before_filter, and then switching back to the previous tenant on an after_filter?

I haven't tried to reproduce anything, just a thought