Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple connections in ActionCable

I have two devise authentication models in my app and want to create a chat amongst them. Can someone help me write the connection for the users? Below is what I have. I wanted to check if I can have two connections reject the connections for different users based on their individual logins. Any help is appreciated.

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    identified_by :current_supplier

    def connect
      self.current_user = find_verified_user
      self.current_supplier = find_verified_supplier
    end

    private
      def find_verified_user
        if current_user = env['warden'].user('user')
          current_user
        end
      end

      def find_verified_supplier
        if current_supplier = env['warden'].user('supplier')
          current_supplier
        else
          reject_unauthorized_connection
        end
      end
  end
end
like image 741
Saurabh Avatar asked Jan 16 '17 09:01

Saurabh


1 Answers

Adapting a bit from this tutorial:

# app/channels/application_cable/connection.rb

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

    def connect
      find_verified
    end

    protected

    def find_verified
      setup_user     if verified_user
      setup_supplier if verified_supplier

      reject_unauthorized_connection unless [current_supplier, current_user].any?
    end

    def verified_user
      cookies.signed['user.expires_at'].present? &&
        cookies.signed['user.expires_at'] > Time.zone.now
    end

    def verified_supplier
      cookies.signed['supplier.expires_at'].present? &&
        cookies.signed['supplier.expires_at'] > Time.zone.now
    end

    def setup_supplier
      self.current_supplier = Supplier.find_by(id: cookies.signed['supplier.id'])
      logger.add_tags 'ActionCable', "#{current_supplier.model_name.name} #{current_supplier.id}"
    end

    def setup_user
      self.current_user = User.find_by(id: cookies.signed['user.id'])
      logger.add_tags 'ActionCable', "#{current_user.model_name.name} #{current_user.id}"
    end
  end
end

And:

# config/initializers/warden_hooks.rb

Warden::Manager.after_set_user do |user, auth, opts|
  scope = opts[:scope]
  auth.cookies.signed["#{scope}.id"] = user.id
  auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
end

Warden::Manager.before_logout do |_user, auth, opts|
  scope = opts[:scope]
  auth.cookies.signed["#{scope}.id"] = nil
  auth.cookies.signed["#{scope}.expires_at"] = nil
end
like image 157
Daniel Avatar answered Oct 30 '22 18:10

Daniel