Search code examples
ruby-on-railsactioncableapartment-gem

Action cable in rails application with subdomain - apartment gem isn't working


Rails 5, apartment gem

action cable connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user, :tenant

    def connect
      self.tenant = request.subdomain
      Apartment::Tenant.switch!(tenant)

      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.try(:email) || 'Unauthenticated User'
    end

    protected

    def find_verified_user # this checks whether a user is authenticated with devise
      if verified_user = env['warden'].user
        verified_user
      else
        # May have public users accessing the channels
        # reject_unauthorized_connection
      end
    end
  end
end

environments/production.rb

config.action_cable.allowed_request_origins = [ /https:\/\/(.*).mydomain.com/ ]

Tried above code reference taken from these links: Link 1 and Link 2 but not working.

In production: request.subdomain is nil(tried with hot coding some tenant values, but not working)

In development: request.subdomain gives the tenant name, but actual request isn't working.

Any help?


Solution

  • Fixed this issue:

    request.subdomain isn't working and returns "". Alternatively I passed the tenant value through query string

    const getWebSocketURL = () => {
        var protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
        var host = window.location.host;
        var path = '/cable';
        var url = protocol + host + path;
        return `${url}?tenant=mytenant`;
    };
    

    and

    const wsUrl = getWebSocketURL();
    const cable = ActionCable.createConsumer(wsUrl);
    

    connection.rb:

    self.tenant = request.params[:tenant]
    

    Also inside yours channels in every method you first line should be

    Apartment::Tenant.switch!(tenant)
    

    here you can get the tenant values from room

    see these links too: how-to-set-tenant-in-actioncable
    rails-actioncable-request-origins-subdomain