ErwinM / acts_as_tenant

Easy multi-tenancy for Rails in a shared database setup.
MIT License
1.53k stars 262 forks source link

How to set user before require_tenant check? #304

Open seanarnold opened 1 year ago

seanarnold commented 1 year ago

I want to conditionally set require_tenant based on a user attribute. i.e all non-admins need to have a Tenant explicitly set.

ActsAsTenant.configure do |config|
  config.require_tenant = lambda do
    Current.user && !Current.user.admin?
  end
end
class ApplicationController < ActionController::Base
  set_current_tenant_through_filter
  before_action :authenticate_user!
  before_action :set_tenant_record

  def authenticate_user!
    ActsAsTenant.without_tenant do
      super
      # Set a global var as `current_user` isn't available in initialiser 
      Current.user = current_user
    end
  end

  def set_tenant_record
    set_current_tenant(current_user.tenant)
  end
end

However require_tenant is evaluated when authenticate_user! is called, even though it's within a without_tenant block. As Current.user is nil, the lamba evaluates to false.

How do I set my Devise user before the require_tenant lambda is evaluated?

omarluq commented 1 year ago

running into a similar issue, I have a primary and a secondary tenancy and need to determine which one to apply by looking into the current_user roles first